Fix more security issues
[vnfsdk/refrepo.git] / vnfmarket-be / vnf-sdk-marketplace / src / main / java / org / onap / vnfsdk / marketplace / common / JsonUtil.java
1 /*
2  * Copyright 2016 Huawei Technologies Co., Ltd.
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package org.onap.vnfsdk.marketplace.common;
18
19 import java.io.IOException;
20
21 import org.codehaus.jackson.map.DeserializationConfig;
22 import org.codehaus.jackson.map.ObjectMapper;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 /**
27  * Json tools class, packaging a number of commonly used Json methods.<br>
28  * 
29  * @author
30  * @version GSO 0.5 2016-08-26
31  */
32 public final class JsonUtil {
33
34     private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
35
36     private JsonUtil() {
37     }
38
39     /**
40      * Convert object to JSON.<br>
41      * 
42      * @param obj The object to be converted
43      * @return The JSON string
44      * @since GSO 0.5
45      */
46     public static String toJson(Object obj) {
47         try {
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);
52         }
53     }
54
55     /**
56      * Convert JSON to object.<br>
57      * 
58      * @param jsonStr The JSON to be converted
59      * @param objClass The object class
60      * @return The objClass object
61      * @since GSO 0.5
62      */
63     public static <T> T fromJson(String jsonStr, Class<T> objClass) {
64         try {
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);
72         }
73     }
74
75 }