|
2 | 2 |
|
3 | 3 | import java.math.BigDecimal;
|
4 | 4 | import java.math.BigInteger;
|
| 5 | +import java.util.TreeMap; |
5 | 6 |
|
6 | 7 | import com.fasterxml.jackson.databind.*;
|
| 8 | +import com.fasterxml.jackson.databind.json.JsonMapper; |
7 | 9 |
|
8 | 10 | public class JsonNodeFactoryTest extends NodeTestBase
|
9 | 11 | {
|
10 | 12 | private final ObjectMapper MAPPER = objectMapper();
|
11 | 13 |
|
| 14 | + static class SortingNodeFactory extends JsonNodeFactory { |
| 15 | + private static final long serialVersionUID = 1L; |
| 16 | + |
| 17 | + @Override |
| 18 | + public ObjectNode objectNode() { |
| 19 | + return new ObjectNode(this, new TreeMap<String, JsonNode>()); |
| 20 | + } |
| 21 | + } |
| 22 | + |
12 | 23 | public void testSimpleCreation()
|
13 | 24 | {
|
14 | 25 | JsonNodeFactory f = MAPPER.getNodeFactory();
|
@@ -36,4 +47,29 @@ public void testSimpleCreation()
|
36 | 47 |
|
37 | 48 | assertTrue(f.missingNode().isMissingNode());
|
38 | 49 | }
|
| 50 | + |
| 51 | + // 09-Sep-2020, tatu: Let's try something more useful: auto-sorting |
| 52 | + // Tree Model! |
| 53 | + |
| 54 | + public void testSortingObjectNode() throws Exception |
| 55 | + { |
| 56 | + final String SIMPLE_INPUT = "{\"b\":2,\"a\":1}"; |
| 57 | + |
| 58 | + // First, by default, ordering retained: |
| 59 | + assertEquals(SIMPLE_INPUT, |
| 60 | + MAPPER.writeValueAsString(MAPPER.readTree(SIMPLE_INPUT))); |
| 61 | + |
| 62 | + // But can change easily |
| 63 | + ObjectMapper mapper = JsonMapper.builder() |
| 64 | + .nodeFactory(new SortingNodeFactory()) |
| 65 | + .build(); |
| 66 | + JsonNode sort = mapper.readTree(SIMPLE_INPUT); |
| 67 | + assertEquals("{\"a\":1,\"b\":2}", MAPPER.writeValueAsString(sort)); |
| 68 | + |
| 69 | + final String BIGGER_INPUT = a2q("['x',{'b':1,'c':true,'a':3},false]"); |
| 70 | + final String BIGGER_OUTPUT = a2q("['x',{'a':3,'b':1,'c':true},false]"); |
| 71 | + |
| 72 | + assertEquals(BIGGER_OUTPUT, |
| 73 | + MAPPER.writeValueAsString(mapper.readTree(BIGGER_INPUT))); |
| 74 | + } |
39 | 75 | }
|
0 commit comments