How to compare two JSON Strings for equality using GSON?

前端 未结 2 1053
猫巷女王i
猫巷女王i 2021-01-12 11:13

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

相关标签:
2条回答
  • 2021-01-12 12:00

    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.

    0 讨论(0)
  • 2021-01-12 12:05

    I don't believe that Gson library makes any statements that the JSON output from two equal JSON elements will be the same, mostly due to the order of properties in objects, since the standard doesn't require any kind of order. Gson library itself doesn't offer a functionality to compare JSON elements or serialized representation thereof. One can write a function that will compare two JSON elements and properly descend into the underlying compound structures (i.e. arrays and objects).

    I was able to find this article here that seems to contain a working comparison function.

    0 讨论(0)
提交回复
热议问题