1 /*******************************************************************************
2 * Copyright 2016-2017 ZTE, Inc. and others.
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
13 ******************************************************************************/
14 package org.onap.msb.apiroute.wrapper.util;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
19 import com.fasterxml.jackson.core.type.TypeReference;
20 import com.fasterxml.jackson.databind.ObjectMapper;
21 import com.fasterxml.jackson.databind.SerializationFeature;
24 public class JacksonJsonUtil {
26 private static final Logger logger = LoggerFactory.getLogger(JacksonJsonUtil.class);
28 private volatile static ObjectMapper mapper = null;
30 private static ObjectMapper getMapperInstance() {
32 synchronized (JacksonJsonUtil.class) {
34 mapper = new ObjectMapper();
42 * from java object to json
48 public static String beanToJson(Object obj) throws Exception {
51 ObjectMapper objectMapper = getMapperInstance();
52 objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
53 json = objectMapper.writeValueAsString(obj);
61 * from json to java object
68 public static Object jsonToBean(String json, Class<?> cls) throws Exception {
71 ObjectMapper objectMapper = getMapperInstance();
72 objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
73 vo = objectMapper.readValue(json, cls);
75 } catch (Exception e) {
76 logger.error(cls + " JsonTobean faild");
77 throw new Exception(cls + " JsonTobean faild");
83 * from json to java List
90 public static <T> T jsonToListBean(String json, TypeReference<T> valueTypeRef) {
93 ObjectMapper objectMapper = getMapperInstance();
96 return objectMapper.readValue(json, valueTypeRef);
98 } catch (Exception e) {
99 String errorMsg = " JsonTobean faild:" + e.getMessage();
100 logger.error(errorMsg);