b647fa3a659d2404c6bcb4cd7f12f73fed10dba7
[sdc.git] /
1 package org.openecomp.sdc.securityutil;
2
3 import com.fasterxml.jackson.annotation.JsonInclude;
4 import com.fasterxml.jackson.databind.DeserializationFeature;
5 import com.fasterxml.jackson.databind.ObjectMapper;
6 import com.fasterxml.jackson.databind.SerializationFeature;
7 import org.slf4j.Logger;
8 import org.slf4j.LoggerFactory;
9
10 import java.io.IOException;
11
12 public class RepresentationUtils {
13
14     private static final Logger log = LoggerFactory.getLogger(RepresentationUtils.class.getName());
15
16     /**
17      * Build JSON Representation of given Object
18      *
19      * @param elementToRepresent
20      * @return
21      * @throws IOException
22      */
23     public static <T> String toRepresentation(T elementToRepresent) throws IOException {
24
25         ObjectMapper mapper = new ObjectMapper();
26         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
27         mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
28         return mapper.writeValueAsString(elementToRepresent);
29     }
30
31     /**
32      * Convert JSON representation to given class
33      *
34      * @param json
35      * @param clazz
36      * @param <T>
37      * @return
38      */
39     public static <T> T fromRepresentation(String json, Class<T> clazz) {
40         ObjectMapper mapper = new ObjectMapper();
41         T object = null;
42         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
43         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
44         mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
45         try {
46             object = mapper.readValue(json, clazz);
47         } catch (Exception e) {
48             log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e);
49         } // return null in case of exception
50
51         return object;
52     }
53 }