• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package com.fasterxml.jackson.databind.node;
2 
3 import java.io.IOException;
4 
5 import com.fasterxml.jackson.databind.JsonNode;
6 import com.fasterxml.jackson.databind.ObjectReader;
7 import com.fasterxml.jackson.databind.ObjectWriter;
8 import com.fasterxml.jackson.databind.json.JsonMapper;
9 
10 /**
11  * Helper class used to implement <code>toString()</code> method for
12  * {@link BaseJsonNode}, by embedding a private instance of
13  * {@link JsonMapper}, only to be used for node serialization.
14  *
15  * @since 2.10 (but not to be included in 3.0)
16  */
17 final class InternalNodeMapper {
18     private final static JsonMapper JSON_MAPPER = new JsonMapper();
19 
20     private final static ObjectWriter STD_WRITER = JSON_MAPPER.writer();
21     private final static ObjectWriter PRETTY_WRITER = JSON_MAPPER.writer()
22             .withDefaultPrettyPrinter();
23 
24     private final static ObjectReader NODE_READER = JSON_MAPPER.readerFor(JsonNode.class);
25 
26     // // // Methods for `JsonNode.toString()` and `JsonNode.toPrettyString()`
27 
nodeToString(JsonNode n)28     public static String nodeToString(JsonNode n) {
29         try {
30             return STD_WRITER.writeValueAsString(n);
31         } catch (IOException e) { // should never occur
32             throw new RuntimeException(e);
33         }
34     }
35 
nodeToPrettyString(JsonNode n)36     public static String nodeToPrettyString(JsonNode n) {
37         try {
38             return PRETTY_WRITER.writeValueAsString(n);
39         } catch (IOException e) { // should never occur
40             throw new RuntimeException(e);
41         }
42     }
43 
44     // // // Methods for JDK serialization support of JsonNodes
45 
valueToBytes(Object value)46     public static byte[] valueToBytes(Object value) throws IOException {
47         return JSON_MAPPER.writeValueAsBytes(value);
48     }
49 
bytesToNode(byte[] json)50     public static JsonNode bytesToNode(byte[] json) throws IOException {
51         return NODE_READER.readValue(json);
52     }
53 }
54