JsonNodeComparator implements Comparator<JsonNode>, Serializable { public int compare(final JsonNode o1, final JsonNode o2) { final int r = orderValue(o1) - orderValue(o2); if (r != 0) return r; final JsonNodeType type = o1 != null ? o1.getNodeType() : null; if (type == null || type == JsonNodeType.MISSING || type == JsonNodeType.NULL) return 0; if (type == JsonNodeType.BOOLEAN) return Boolean.compare(o1.asBoolean(), o2.asBoolean()); if (type == JsonNodeType.NUMBER) { final double a = o1.asDouble(); final double b = o2.asDouble(); if (Double.isNaN(a)) return -1; if (Double.isNaN(b)) return 1; return Double.compare(a, b); } if (type == JsonNodeType.STRING || type == JsonNodeType.BINARY) return o1.asText().compareTo(o2.asText()); if (type == JsonNodeType.ARRAY) { final int s1 = o1.size(); final int s2 = o2.size(); final int s = Math.min(s1, s2); for (int i = 0; i < s; ++i) { final int rr = compare(o1.get(i), o2.get(i)); if (rr != 0) return rr; } return Integer.compare(s1, s2); } if (type == JsonNodeType.OBJECT) { final List<String> names1 = Lists.newArrayList(o1.fieldNames()); final List<String> names2 = Lists.newArrayList(o2.fieldNames()); Collections.sort(names1); Collections.sort(names2); final int s = Math.min(names1.size(), names2.size()); for (int i = 0; i < s; ++i) { final int rr = names1.get(i).compareTo(names2.get(i)); if (rr != 0) return rr; } final int rr = Integer.compare(names1.size(), names2.size()); if (rr != 0) return rr; for (final String name : names1) { final int rrr = compare(o1.get(name), o2.get(name)); if (rrr != 0) return rrr; } return 0; } throw new IllegalArgumentException("Unknown JsonNodeType: " + type); }  static JsonNodeComparator getInstance(); int compare(final JsonNode o1, final JsonNode o2);  }
@Test public void test() throws IOException { final ObjectMapper mapper = new ObjectMapper(); final JsonNode j3 = mapper.readTree("3"); final JsonNode j10 = mapper.readTree("10"); final JsonNode jhoge = mapper.readTree("\"hoge\""); final JsonNodeComparator sut = new JsonNodeComparator(); assertTrue(sut.compare(j3, j10) < 0); assertTrue(sut.compare(j3, jhoge) < 0); assertTrue(sut.compare(j10, jhoge) < 0); final List<JsonNode> nodes = new ArrayList<>(Arrays.asList(j3, jhoge, j10)); nodes.sort(sut); assertEquals(Arrays.asList(j3, j10, jhoge), nodes); }