Java 当条目的顺序不断变化时如何比较两个 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30325042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:27:17  来源:igfitidea点击:

How to compare two JSON strings when the order of entries keep changing

javajsonstringequalsjsonobject

提问by Green

I have a string like - {"state":1,"cmd":1}, I need to compare this with generated output but in the generated output the order keeps changing i.e. sometimes its {"state":1,"cmd":1}other times its {"cmd":1,"state":1}.

我有这样一个字符串- {"state":1,"cmd":1},我需要产生的输出,但在生成的输出顺序不断变化的,有时它即要比较这{"state":1,"cmd":1}其他倍{"cmd":1,"state":1}

Currently I was using equals()method to compare, What can be better way in this scenario to validate the two strings. My concern is just that both entries are present in string, order is not imp.

目前我正在使用equals()方法进行比较,在这种情况下有什么更好的方法来验证两个字符串。我担心的是这两个条目都以字符串形式存在,顺序不是imp。

采纳答案by Sharon Ben Asher

Hymanson Json parserhas a nice feature that it can parse a Json String into a Map. You can then query the entries or simply ask on equality:

Hymanson Json 解析器有一个很好的功能,它可以将 Json 字符串解析为 Map。然后,您可以查询条目或简单地询问相等性:

import com.fasterxml.Hymanson.databind.ObjectMapper;

import java.util.*;

public class Test
{
    public static void main(String... args)
    {
        String input1 = "{\"state\":1,\"cmd\":1}";
        String input2 = "{\"cmd\":1,\"state\":1}";
        ObjectMapper om = new ObjectMapper();
        try {
            Map<String, Object> m1 = (Map<String, Object>)(om.readValue(input1, Map.class));
            Map<String, Object> m2 = (Map<String, Object>)(om.readValue(input2, Map.class));
            System.out.println(m1);
            System.out.println(m2);
            System.out.println(m1.equals(m2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output is

输出是

{state=1, cmd=1}
{cmd=1, state=1}
true

回答by Siva Sonai

Try this

尝试这个

 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 

I trust this is helpful to you.

我相信这对你有帮助。

回答by cн?dk

You can simply use a class to define your object and JSONObjectto parse your JSON object and get its properties:

您可以简单地使用一个类来定义您的对象和JSONObject来解析您的 JSON 对象并获取其属性:

Java Class:

Java类:

public class MyObject{
     private String state; //either int or String
     private String cmd;
     //getters and setters
}

Your parsing should be like this:

你的解析应该是这样的:

MyObject obj = new MyObject();
JSONParser jsonParser = new JSONParser();
 // input is your string here
JSONObject jsonObject = (JSONObject) jsonParser.parse(input);

//get properties here and set them in your object
obj.setState(jsonObject.get("state"));
obj.setCmd(jsonObject.get("cmd"));

And then when you have the two objects you can easily compare their properties.

然后当您拥有这两个对象时,您可以轻松比较它们的属性。

回答by Rockstar

You can also use Gson API

你也可以使用 Gson API

 JsonParser parser = new JsonParser();
 JsonElement o1 = parser.parse("{\"state\":1,\"cmd\":1}");
 JsonElement o2 = parser.parse("{\"cmd\":1,\"state\":1}");
 System.out.println(o1.equals(o2));