Is there a quick way to compare two json arrays?

11,940 views
Skip to first unread message

Michael Yang

unread,
Jul 31, 2012, 3:35:11 PM7/31/12
to googl...@googlegroups.com
I'm wondering if there is a quick API in gson to check if two json arrays have the same item.

For example, I have two json strings which have the same object but in different order:
Object 1:
[{"key1":"value1"}, {"key2":"value2"}, {"key3":"value3"}]
Object 2:
[{"key3":"value3"}, {"key1":"value1"}, {"key2":"value2"}] 

Do I have to parse the string into arrays and compare each item in two arrays for equality?

Thanks,
Michael.

Brandon Mintern

unread,
Jul 31, 2012, 5:50:12 PM7/31/12
to googl...@googlegroups.com
The most concise thing (though perhaps not the most efficient) would
be to dump their constituent JsonElements into ordinary Java Sets.
Then you can use the normal Set API (e.g. contains, equals) to get the
information you want.

CompareArrays.java
====================
import java.util.*;
import com.google.gson.*;

public class CompareArray {
static Set<JsonElement> setOfElements(JsonArray arr) {
Set<JsonElement> set = new HashSet<JsonElement>();
for (JsonElement j: arr) {
set.add(j);
}
return set;
}

public static void main(String[] args) {
JsonParser parser = new JsonParser();
Set<JsonElement> arr1elems =
setOfElements(parser.parse(args[0]).getAsJsonArray());
Set<JsonElement> arr2elems =
setOfElements(parser.parse(args[1]).getAsJsonArray());
System.out.println("Arrays match? " + arr1elems.equals(arr2elems));
}
}
====================

$ java -cp .:gson-2.2.2.jar CompareArray '[{"key1":"value1"},
{"key2":"value2"}, {"key3":"value3"}]' '[{"key3":"value3"},
{"key1":"value1"}, {"key2":"value2"}]'
Arrays match? true

Michael Yang

unread,
Aug 1, 2012, 10:14:58 AM8/1/12
to googl...@googlegroups.com
Thank you Brandon! I think Set is the right way to go.
Reply all
Reply to author
Forward
0 new messages