0

I am trying compare two json string with mixed elements in array. I found many answers(1,2) how compare two json but not with array. You can help me?

My code:

Passed

@Test
public void test() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node1 = mapper.readTree("{\"a\" : [{\"a\" : 2},{\"s\" : 5}], \"b\" : 2}");
    JsonNode node2 = mapper.readTree("{\"b\" : 2, \"a\" : [{\"a\" : 2},{\"s\" : 5}]}");
    assertThat(node1.equals(node2), is(true));
}

Failed, but why? How can compare json?

@Test
public void test() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node1 = mapper.readTree("{\"a\" : [{\"a\" : 2},{\"s\" : 5}], \"b\" : 2}");
    JsonNode node2 = mapper.readTree("{\"b\" : 2, \"a\" : [{\"s\" : 5},{\"a\" : 2}]}");
    assertThat(node1.equals(node2), is(true));
}

Thanks.

Community
  • 1
  • 1
boden
  • 1,621
  • 1
  • 21
  • 42
  • 2
    I'm not surprised by this. The ordering of JSON properties is normally not considered to be important - whereas the ordering of elements in a JSON array *is* considered important. Why do you consider it *unimportant*? – Jon Skeet Jul 12 '16 at 13:52
  • @JonSkeet i received similar json from other server and array elements always in a different order. But how i can compare json in this case? – boden Jul 12 '16 at 14:00
  • Well, is there something simple you could sort the array by? – Jon Skeet Jul 12 '16 at 14:09
  • @JonSkeet how i can get array? – boden Jul 12 '16 at 14:12
  • Well have you looked at the documentation for JsonNode? At this point the question doesn't seem to be as much about comparison as basic use of the API. – Jon Skeet Jul 12 '16 at 14:22
  • Hi @JonSkeet, I am found lib with `org.skyscreamer.jsonassert.JSONCompare` class where can compare JSON with different elements order in array – boden Jul 13 '16 at 09:32

0 Answers0