2 * Copyright 2016 Huawei Technologies Co., Ltd.
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.vnfsdk.marketplace.common;
19 import java.io.IOException;
21 import org.codehaus.jackson.map.DeserializationConfig;
22 import org.codehaus.jackson.map.ObjectMapper;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
27 * Json tools class, packaging a number of commonly used Json methods.<br>
30 * @version GSO 0.5 2016-08-26
32 public final class JsonUtil {
34 private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
40 * Convert object to JSON.<br>
42 * @param obj The object to be converted
43 * @return The JSON string
46 public static String toJson(Object obj) {
48 return new ObjectMapper().writeValueAsString(obj);
49 } catch (IOException ex) {
50 LOGGER.error("Parser to json error.", ex);
51 throw new IllegalArgumentException("Parser obj to json error, obj = " + obj, ex);
56 * Convert JSON to object.<br>
58 * @param jsonStr The JSON to be converted
59 * @param objClass The object class
60 * @return The objClass object
63 public static <T> T fromJson(String jsonStr, Class<T> objClass) {
65 ObjectMapper mapper = new ObjectMapper();
66 mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
67 return mapper.readValue(jsonStr, objClass);
68 } catch (IOException ex) {
69 LOGGER.error("Parser to object error.", ex);
70 throw new IllegalArgumentException(
71 "Parser json to object error, json = " + jsonStr + ", expect class = " + objClass, ex);