Add wso2bpel-ext code
[vfc/nfvo/wfengine.git] / wso2bpel-ext / wso2bpel-core / wso2bpel-mgr / src / main / java / org / openo / carbon / bpel / util / JsonUtil.java
1 /**
2  * Copyright 2016 [ZTE] and others.
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 package org.openo.carbon.bpel.util;
17
18 import java.io.IOException;
19 import java.io.StringWriter;
20
21 import com.fasterxml.jackson.core.JsonFactory;
22 import com.fasterxml.jackson.core.JsonGenerator;
23 import com.fasterxml.jackson.core.JsonParseException;
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import com.fasterxml.jackson.databind.JavaType;
26 import com.fasterxml.jackson.databind.JsonMappingException;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29
30 public class JsonUtil {
31
32   @SuppressWarnings("deprecation")
33   public static String bean2Json(Object obj) throws IOException {
34     ObjectMapper mapper = new ObjectMapper();
35     StringWriter sw = new StringWriter();
36     JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
37     mapper.writeValue(gen, obj);
38     gen.close();
39     return sw.toString();
40   }
41
42   public static <T> T json2Bean(String jsonStr, Class<T> objClass)
43       throws JsonParseException, JsonMappingException, IOException {
44     ObjectMapper mapper = new ObjectMapper();
45     return mapper.readValue(jsonStr, objClass);
46   }
47
48   @SuppressWarnings("deprecation")
49   public static <T> T readJson(String jsonStr, Class<?> collectionClass, Class<?>... elementClasses)
50       throws Exception {
51     ObjectMapper mapper = new ObjectMapper();
52     JavaType javaType =
53         mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
54     return mapper.readValue(jsonStr, javaType);
55   }
56
57   public static JsonNode getJsonNode(String json) throws JsonProcessingException, IOException {
58     return new ObjectMapper().readTree(json);
59   }
60
61 }