2 * Copyright 2016 ZTE Corporation.
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.carbon.bpel.util;
18 import java.io.IOException;
19 import java.io.StringWriter;
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;
30 public class JsonUtil {
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);
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);
48 @SuppressWarnings("deprecation")
49 public static <T> T readJson(String jsonStr, Class<?> collectionClass, Class<?>... elementClasses)
51 ObjectMapper mapper = new ObjectMapper();
53 mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
54 return mapper.readValue(jsonStr, javaType);
57 public static JsonNode getJsonNode(String json) throws JsonProcessingException, IOException {
58 return new ObjectMapper().readTree(json);