简体   繁体   中英

Comparing 2 (unordered) JSONObjects in Java?

Supposed i have 2 json files and i have 2 JSONObject-s (1 to represent each file) and the files represent the same data but in DIFFERENT ORDER of the blocks in the file.

for example:

file1.json

name: {

    entry1
    entry3
    entry2

}

file2.json

name: {

    entry2
    entry1
    entry3

}

Where entry-i in each file is the same.

How can i perform equals on them even though the order is different ?

Thanks

Translate the whole JSON Model to Java Objects. In your example every "entry" simply could be a string. If it's more complex than you have to implement something like POJOs for that. Those POJOs should have equals and hashCode Methods (be aware of their contract )

Then simply put all the entries of every JSON into a HashSet (which doesn't have any order -> click ) and compare the HashSets with equals to each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM