How to compare two JSON strings for equality using GSON?

I am trying to compare two JSON strings for equality. I found this solution that Jackson uses as shown below, but in my entire project I use GSON, so I need to do the same using GSON.

ObjectMapper mapper = new ObjectMapper();
JsonNode tree1 = mapper.readTree(jsonString1);
JsonNode tree2 = mapper.readTree(jsonString2);
if (tree1.equals(tree2)) { 
  // yes, contents are equal -- note, ordering of arrays matters, objects not
} else { 
  // not equal
}

Is there a way to compare two JSON strings for equality using GSON?

+4
source share
1 answer

According to this answer you can use this:

JsonParser parser = new JsonParser();
JsonElement o1 = parser.parse("{a : {a : 2}, b : 2}");
JsonElement o2 = parser.parse("{b : 2, a : {a : 2}}");
assertEquals(o1, o2);

Unfortunately, I guess this is not as clean as you hoped, but it should work.

( GSON), , , , .

+5

All Articles