2 * Copyright 2016 2015-2016 ZTE, Inc. and others. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.openo.msb.wrapper.util;
18 import java.util.List;
20 import org.openo.msb.api.ApiRouteInfo;
21 import org.openo.msb.api.RouteServer;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
25 import com.fasterxml.jackson.core.type.TypeReference;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import com.fasterxml.jackson.databind.SerializationFeature;
30 public class JacksonJsonUtil {
32 private static final Logger logger = LoggerFactory.getLogger(JacksonJsonUtil.class);
34 private static ObjectMapper mapper;
37 public static synchronized ObjectMapper getMapperInstance() {
39 mapper = new ObjectMapper();
45 * from java object to json
50 public static String beanToJson(Object obj) throws Exception {
53 ObjectMapper objectMapper = getMapperInstance();
54 objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
55 json =objectMapper.writeValueAsString(obj);
56 } catch (Exception e) {
57 logger.error("Class beanToJson faild");
58 throw new Exception("Class beanToJson faild");
66 * from json to java object
72 public static Object jsonToBean(String json, Class<?> cls) throws Exception {
75 ObjectMapper objectMapper = getMapperInstance();
76 objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
77 vo = objectMapper.readValue(json, cls);
79 } catch (Exception e) {
80 logger.error(cls+" JsonTobean faild");
81 throw new Exception(cls+" JsonTobean faild");
87 * from json to java List
92 public static List<ApiRouteInfo> jsonToListBean(String json) throws Exception {
93 List<ApiRouteInfo> vo =null;
96 ObjectMapper objectMapper = getMapperInstance();
99 vo = objectMapper.readValue(json, new TypeReference<List<ApiRouteInfo>>() {});
101 } catch (Exception e) {
102 throw new Exception( "JSON_TO_BEAN_FAILD");
107 public static void main(String[] args) {
108 RouteServer server=new RouteServer("127.0.0.1","80");
110 String json=beanToJson(server);
111 System.out.println(json);
112 } catch (Exception e) {
113 // TODO Auto-generated catch block