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

Gre*_*een 13 java string json equals jsonobject

我有一个类似的字符串 - {"state":1,"cmd":1},我需要将其与生成的输出进行比较,但在生成的输出中,顺序会不断变化,即有时它的{"state":1,"cmd":1}其他时间{"cmd":1,"state":1}.

目前我正在使用equals()方法进行比较,在这种情况下可以更好地验证两个字符串.我担心的是两个条目都存在于字符串中,顺序不是imp.

Roc*_*tar 13

您也可以使用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));
Run Code Online (Sandbox Code Playgroud)

  • 适用于Gson 2.2.4 (3认同)

Sha*_*her 11

Jackson Json解析器有一个很好的功能,它可以将Json String解析为Map.然后,您可以查询条目或仅询问相等性:

import com.fasterxml.jackson.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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是

{state=1, cmd=1}
{cmd=1, state=1}
true
Run Code Online (Sandbox Code Playgroud)

  • 它不适用于json有效负载中的列表 (6认同)