View Javadoc
1   package com.guinetik.rr.json;
2   
3   import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
4   import com.fasterxml.jackson.annotation.JsonInclude;
5   import com.fasterxml.jackson.annotation.PropertyAccessor;
6   import com.fasterxml.jackson.core.JsonProcessingException;
7   import com.fasterxml.jackson.core.type.TypeReference;
8   import com.fasterxml.jackson.databind.DeserializationFeature;
9   import com.fasterxml.jackson.databind.JsonNode;
10  import com.fasterxml.jackson.databind.ObjectMapper;
11  import com.fasterxml.jackson.databind.SerializationFeature;
12  
13  import java.io.BufferedReader;
14  import java.io.IOException;
15  import java.io.InputStreamReader;
16  import java.net.HttpURLConnection;
17  import java.util.List;
18  import java.util.Map;
19  
20  /**
21   * Pre-configured Jackson {@link ObjectMapper} with utility methods for JSON operations.
22   *
23   * <p>This class extends Jackson's ObjectMapper with RocketRest-specific configuration and
24   * provides convenient static methods for common JSON serialization and deserialization tasks.
25   *
26   * <h2>Default Configuration</h2>
27   * <ul>
28   *   <li>Field visibility: ANY (serializes private fields)</li>
29   *   <li>Getter/Setter visibility: NONE (ignores getters/setters)</li>
30   *   <li>Indented output: enabled</li>
31   *   <li>Unknown properties: ignored</li>
32   *   <li>Null values: excluded from output</li>
33   * </ul>
34   *
35   * <h2>Object Serialization</h2>
36   * <pre class="language-java"><code>
37   * User user = new User("John", "john@example.com");
38   *
39   * // To JSON string (indented)
40   * String json = JsonObjectMapper.toJsonString(user);
41   *
42   * // To JSON string (compact)
43   * String compact = JsonObjectMapper.toJsonStringNoIdent(user);
44   * </code></pre>
45   *
46   * <h2>Object Deserialization</h2>
47   * <pre class="language-java"><code>
48   * String json = "{\"name\":\"John\",\"email\":\"john@example.com\"}";
49   *
50   * // To typed object
51   * User user = JsonObjectMapper.jsonToObject(json, User.class);
52   *
53   * // To Map
54   * Map&lt;String, Object&gt; map = JsonObjectMapper.jsonToMap(json);
55   *
56   * // To List of Maps
57   * String arrayJson = "[{\"id\":1},{\"id\":2}]";
58   * List&lt;Map&lt;String, Object&gt;&gt; list = JsonObjectMapper.jsonToListOfMap(arrayJson);
59   * </code></pre>
60   *
61   * <h2>JsonNode Operations</h2>
62   * <pre class="language-java"><code>
63   * JsonNode node = JsonObjectMapper.getJsonNode(json);
64   * String name = node.get("name").asText();
65   *
66   * Map&lt;String, Object&gt; map = JsonObjectMapper.jsonNodeToMap(node);
67   * </code></pre>
68   *
69   * <h2>Singleton Access</h2>
70   * <pre class="language-java"><code>
71   * // Get pre-configured singleton instance
72   * ObjectMapper mapper = JsonObjectMapper.get();
73   *
74   * // Get fresh default-configured mapper
75   * ObjectMapper fresh = JsonObjectMapper.getDefault();
76   * </code></pre>
77   *
78   * @author guinetik &lt;guinetik@gmail.com&gt;
79   * @see ObjectMapper
80   * @since 1.0.0
81   */
82  public class JsonObjectMapper extends ObjectMapper {
83  
84      private static final long serialVersionUID = 1L;
85  
86      private static class ObjectMapperInstanceHolder {
87          static final ObjectMapper INSTANCE = getDefault();
88      }
89  
90      public JsonObjectMapper() {
91          setVisibilityChecker(
92                  getVisibilityChecker().withVisibility(PropertyAccessor.FIELD, Visibility.ANY)
93                          .withVisibility(PropertyAccessor.GETTER, Visibility.NONE).withVisibility(
94                                  PropertyAccessor.SETTER, Visibility.NONE
95                          ));
96          enable(SerializationFeature.INDENT_OUTPUT);
97      }
98  
99      private static String toJsonString(Object model, boolean ident) {
100         ObjectMapper mapper = JsonObjectMapper.get();
101         try {
102             if (ident)
103                 mapper.enable(SerializationFeature.INDENT_OUTPUT);
104             //System.out.println(modelStr);
105             return mapper.writeValueAsString(model);
106         } catch (JsonProcessingException e) {
107             e.printStackTrace();
108             return null;
109         }
110     }
111 
112     public static JsonNode getJsonNode(String json) {
113         try {
114             return JsonObjectMapper.get().readValue(json, JsonNode.class);
115         } catch (IOException e) {
116             e.printStackTrace();
117         }
118         return null;
119     }
120 
121     public static Map<String, Object> jsonToMap(String json) {
122         return JsonObjectMapper.get().convertValue(json, new TypeReference<Map<String, Object>>() {
123         });
124     }
125 
126     public static Map<String, Object> jsonNodeToMap(JsonNode json) {
127         return JsonObjectMapper.get().convertValue(json, new TypeReference<Map<String, Object>>() {
128         });
129     }
130 
131     public static <T> T jsonToObject(String json, Class<T> type) {
132 
133         try {
134             return JsonObjectMapper.getDefault().readValue(json, type);
135         } catch (Exception e) {
136             e.printStackTrace();
137         }
138         return null;
139     }
140 
141     public static List<Map<String, Object>> jsonToListOfMap(String json) {
142         ObjectMapper mapper = JsonObjectMapper.getDefault();
143         try {
144             return mapper.readValue(json, new TypeReference<List<Map<String, Object>>>() {
145             });
146         } catch (Exception e) {
147             e.printStackTrace();
148         }
149         return null;
150     }
151 
152     public static String toJsonString(Object model) {
153         return toJsonString(model, true);
154     }
155 
156     public static String toJsonStringNoIdent(Object model) {
157         return toJsonString(model, false);
158     }
159 
160     public static ObjectMapper getDefault() {
161         ObjectMapper mapper = new ObjectMapper();
162         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
163         mapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES);
164         mapper.disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS);
165         mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
166         //SerializationConfig config = mapper.getSerializationConfig();
167         //config.withSerializationInclusion(Include.NON_EMPTY);
168         //config.withSerializationInclusion(Include.NON_NULL);
169         return mapper;
170     }
171 
172     public static ObjectMapper get() {
173         return ObjectMapperInstanceHolder.INSTANCE;
174     }
175 
176     public static Map<String, Object> parseResponse(HttpURLConnection connection) throws IOException {
177         try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
178             StringBuilder response = new StringBuilder();
179             String line;
180             while ((line = reader.readLine()) != null) {
181                 response.append(line);
182             }
183             return get().readValue(response.toString(), new TypeReference<Map<String, Object>>() {});
184         }
185     }
186 }