2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright (C) 2017 Amdocs
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
20 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.openecomp.appc.dg.common.utils;
25 import com.fasterxml.jackson.databind.JsonNode;
26 import com.fasterxml.jackson.databind.ObjectMapper;
28 import java.io.IOException;
29 import java.io.Reader;
33 public class JSONUtil {
35 private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
37 public static <T> T fromJson(String json, Class<T> clazz) {
40 return OBJECT_MAPPER.readValue(json, clazz);
41 } catch (IOException e) {
42 throw new RuntimeException(e);
46 public static <T> T fromJson(Reader reader, Class<T> clazz) {
49 return OBJECT_MAPPER.readValue(reader, clazz);
50 } catch (IOException e) {
51 throw new RuntimeException(e);
55 public static String toJson(Object object) {
58 return OBJECT_MAPPER.writeValueAsString(object);
59 } catch (IOException e) {
60 throw new RuntimeException(e);
64 public static Map<String,String> extractPlainValues(String json, String ... names) {
65 if (null == names) return Collections.emptyMap();
66 Map<String,String> values = new HashMap<>();
68 final JsonNode jsonNode = OBJECT_MAPPER.readTree(json);
69 for (String name : names) {
70 values.put(name, jsonNode.path(name).asText());
72 } catch (IOException e) {
73 throw new RuntimeException(e);