2 * Copyright 2016 ZTE, Inc. and others.
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.
17 package org.onap.msb.apiroute.wrapper.util;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
22 import com.fasterxml.jackson.core.type.TypeReference;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.fasterxml.jackson.databind.SerializationFeature;
27 public class JacksonJsonUtil {
29 private static final Logger logger = LoggerFactory.getLogger(JacksonJsonUtil.class);
31 private volatile static ObjectMapper mapper = null;
33 private static ObjectMapper getMapperInstance() {
35 synchronized (JacksonJsonUtil.class) {
37 mapper = new ObjectMapper();
45 * from java object to json
51 public static String beanToJson(Object obj) throws Exception {
54 ObjectMapper objectMapper = getMapperInstance();
55 objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
56 json = objectMapper.writeValueAsString(obj);
64 * from json to java object
71 public static Object jsonToBean(String json, Class<?> cls) throws Exception {
74 ObjectMapper objectMapper = getMapperInstance();
75 objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
76 vo = objectMapper.readValue(json, cls);
78 } catch (Exception e) {
79 logger.error(cls + " JsonTobean faild");
80 throw new Exception(cls + " JsonTobean faild");
86 * from json to java List
93 public static <T> T jsonToListBean(String json, TypeReference<T> valueTypeRef) {
96 ObjectMapper objectMapper = getMapperInstance();
99 return objectMapper.readValue(json, valueTypeRef);
101 } catch (Exception e) {
102 String errorMsg = " JsonTobean faild:" + e.getMessage();
103 logger.error(errorMsg);