2 * Copyright (c) 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.
16 package org.openo.baseservice.roa.util.clientsdk;
18 import org.codehaus.jackson.map.ObjectMapper;
19 import org.codehaus.jackson.type.TypeReference;
21 import net.sf.json.JSON;
23 import java.io.IOException;
26 * JSON parse utilities.
32 * @version SDNO 0.5 28-May-2016
34 public final class JsonUtil {
36 private static final ObjectMapper MAPPER = new ObjectMapper();
39 MAPPER.setDeserializationConfig(MAPPER.getDeserializationConfig()
40 .without(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES));
47 * Parse JSON formated string.<br/>
49 * @param jsonstr: JSON formated string.
50 * @param type: result type.
51 * @return parsed object.
52 * @throws IOException incase error.
55 public static <T> T unMarshal(final String jsonstr, final Class<T> type) throws IOException {
56 return MAPPER.readValue(jsonstr, type);
60 * Parse JSON formatted string (for a generic target type).
63 * @param jsonstr request data.
64 * @param type target type.
65 * @return result object.
66 * @throws IOException incase error.
69 public static <T> T unMarshal(final String jsonstr, final TypeReference<T> type) throws IOException {
70 return MAPPER.readValue(jsonstr, type);
74 * Convert object to JSON format string.
77 * @param srcObj source object.
78 * @return JSON format string.
79 * @throws IOException incase of error.
82 public static String marshal(final Object srcObj) throws IOException {
83 if(srcObj instanceof JSON) {
84 return srcObj.toString();
86 return MAPPER.writeValueAsString(srcObj);
93 * @return parsing mapper
96 public static ObjectMapper getMapper() {