Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two JSON Strings for equality using GSON?

I am trying to compare two JSON Strings for equality. I found this solution which uses Jackson as shown below but in all my project I am using GSON so I need to do the same thing 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 any way to compare two JSON String for equality using GSON?

like image 871
john Avatar asked Sep 04 '14 00:09

john


People also ask

How do you check to two JSON objects is equal?

Comparing json is quite simple, we can use '==' operator, Note: '==' and 'is' operator are not same, '==' operator is use to check equality of values , whereas 'is' operator is used to check reference equality, hence one should use '==' operator, 'is' operator will not give expected result.

Can we compare two JSON objects?

Similarly, we can also compare two JSON objects that contain a list element. It's important to know that two list elements are only compared as equal if they have the same values in the exact same order.

What is difference between JSON and GSON?

The JSON format was originally specified by Douglas Crockford. On the other hand, GSON is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.


1 Answers

According to this answer you could 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'm guessing this isn't quite as clean as you were hoping, but it should work.

In any case it might be helpful to look through the other answers in that thread (although not all use GSON), so if this doesn't work out, perhaps one of those might.

like image 79
Akshay Avatar answered Nov 13 '22 09:11

Akshay