1 /*******************************************************************************
2 * Copyright 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 ******************************************************************************/
15 * Copyright (C) 2015 ZTE, Inc. and others. All rights reserved. (ZTE)
17 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
18 * in compliance with the License. You may obtain a copy of the License at
20 * http://www.apache.org/licenses/LICENSE-2.0
22 * Unless required by applicable law or agreed to in writing, software distributed under the License
23 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
24 * or implied. See the License for the specific language governing permissions and limitations under
27 package org.onap.msb.sdk.discovery.util;
29 import org.onap.msb.sdk.discovery.common.RouteException;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
33 import com.fasterxml.jackson.core.type.TypeReference;
34 import com.fasterxml.jackson.databind.ObjectMapper;
36 public class JacksonJsonUtil {
38 private static final Logger logger = LoggerFactory.getLogger(JacksonJsonUtil.class);
40 private static ObjectMapper mapper;
45 * @param createNew 方式:true,新实例;false,存在的mapper实例
48 public static synchronized ObjectMapper getMapperInstance() {
50 mapper = new ObjectMapper();
62 public static String beanToJson(Object obj) throws RouteException {
65 ObjectMapper objectMapper = getMapperInstance();
66 json = objectMapper.writeValueAsString(obj);
67 } catch (Exception e) {
68 throwsRouteException("Class beanToJson faild", e, "BEAN_TO_JSON_FAILD");
78 * @param json 准备转换的json字符串
83 public static Object jsonToBean(String json, Class<?> cls) throws RouteException {
86 ObjectMapper objectMapper = getMapperInstance();
89 vo = objectMapper.readValue(json, cls);
91 } catch (Exception e) {
92 throwsRouteException(cls + " JsonTobean faild:" + e.getMessage(), e, "JSON_TO_BEAN_FAILD");
98 private static void throwsRouteException(String errorMsg, Exception e, String errorCode) throws RouteException {
99 String msg = errorMsg + ".errorMsg:" + e.getMessage();
101 throw new RouteException(errorMsg, errorCode);