代码之家  ›  专栏  ›  技术社区  ›  Mani

如何在java中比较两个JSON文件的值

  •  0
  • Mani  · 技术社区  · 7 年前

    JSON文件数据如下所示:

    {   "ab_property": [
    {
      "name": "abc",
      "value": "1"
    },
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   chandrakant    7 年前

    我已经解决了你的问题。你也可以直接匹配值使用键,而不是for循环。

    import java.io.FileReader;
    import java.util.Set;
    import org.json.simple.JSONObject;
    import org.json.simple.parser.JSONParser;
    
    public class compareJsonFile {
    
        public static void main(String[] args) throws Exception {
            JSONParser parser = new JSONParser();
            try {
                Object obj = parser.parse(new FileReader("/home/chandrakant/Desktop/json1.json"));
                Object obj1 = parser.parse(new FileReader("/home/chandrakant/Desktop/json2.json"));
                JSONObject jsonObject = (JSONObject) obj;
                JSONObject jsonObject1 = (JSONObject) obj1;
                Set<String> s = jsonObject.keySet();
                for (String str : s) {
                    System.out.println("key:" + str + " : value1:" + jsonObject.get(str) + ":value2:" + jsonObject1.get(str));
                    //compare value of json1 with json2
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    

        2
  •  2
  •   TomVW    7 年前

    JSONassert 是比较JSON对象的常用库。如果这两个文件是相同的(键和值),它适合您的用例。

    String expected = IOUtils.toString(new File("/path/to/expected").toURI(), Charset.defaultCharset()));
    String actual = IOUtils.toString(new File("/path/to/actual").toURI(), Charset.defaultCharset()));
    JSONAssert.assertEquals(expected, actual, false);