|
| 1 | +package com.fasterxml.jackson.databind; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +import com.fasterxml.jackson.databind.node.ArrayNode; |
| 6 | +import com.fasterxml.jackson.databind.node.ObjectNode; |
| 7 | + |
| 8 | +public class TestNodeJDKSerialization extends BaseMapTest |
| 9 | +{ |
| 10 | + private final ObjectMapper MAPPER = newObjectMapper(); |
| 11 | + |
| 12 | + /* |
| 13 | + /********************************************************** |
| 14 | + /* Then something bit different; serialize `JsonNode`(s) |
| 15 | + /********************************************************** |
| 16 | + */ |
| 17 | + |
| 18 | + // [databind#18]: Allow JDK serialization of `ObjectNode` |
| 19 | + public void testObjectNodeSerialization() throws Exception |
| 20 | + { |
| 21 | + ObjectNode root = MAPPER.createObjectNode(); |
| 22 | + root.put("answer", 42); |
| 23 | + ArrayNode arr = root.withArray("matrix"); |
| 24 | + arr.add(1).add(12345678901L).add(true).add("..."); |
| 25 | + ObjectNode misc = root.with("misc"); |
| 26 | + misc.put("value", 0.25); |
| 27 | + |
| 28 | + byte[] ser = jdkSerialize(root); |
| 29 | + JsonNode result = jdkDeserialize(ser); |
| 30 | + assertEquals(root, result); |
| 31 | + } |
| 32 | + |
| 33 | + // [databind#18]: Allow JDK serialization of `ArrayNode` |
| 34 | + public void testArrayNodeSerialization() throws Exception |
| 35 | + { |
| 36 | + ArrayNode root = MAPPER.createArrayNode(); |
| 37 | + root.add(false); |
| 38 | + ObjectNode props = root.addObject(); |
| 39 | + props.put("answer", 42); |
| 40 | + root.add(137); |
| 41 | + |
| 42 | + byte[] ser = jdkSerialize(root); |
| 43 | + JsonNode result = jdkDeserialize(ser); |
| 44 | + assertEquals(root, result); |
| 45 | + } |
| 46 | + |
| 47 | + /* |
| 48 | + /********************************************************** |
| 49 | + /* Helper methods |
| 50 | + /********************************************************** |
| 51 | + */ |
| 52 | + |
| 53 | + protected byte[] jdkSerialize(Object o) throws IOException |
| 54 | + { |
| 55 | + ByteArrayOutputStream bytes = new ByteArrayOutputStream(1000); |
| 56 | + ObjectOutputStream obOut = new ObjectOutputStream(bytes); |
| 57 | + obOut.writeObject(o); |
| 58 | + obOut.close(); |
| 59 | + return bytes.toByteArray(); |
| 60 | + } |
| 61 | + |
| 62 | + @SuppressWarnings("unchecked") |
| 63 | + protected <T> T jdkDeserialize(byte[] raw) throws IOException |
| 64 | + { |
| 65 | + ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(raw)); |
| 66 | + try { |
| 67 | + return (T) objIn.readObject(); |
| 68 | + } catch (ClassNotFoundException e) { |
| 69 | + fail("Missing class: "+e.getMessage()); |
| 70 | + return null; |
| 71 | + } finally { |
| 72 | + objIn.close(); |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments