简体   繁体   English

比较两个具有相同嵌套结构和相同键但值可以不同的 json?

[英]Compare two json which has same nested structure and same keys but values can be different?

For example :例如 :

Json A =>
{
  "customer": {
    "age": 29,
    "fullName": "Emily Jenkins",
    "year":1988,
    "address":{
        "lineOne":"lineOne",
        "lineTwo":"lineTwo"
    }
},
  "handset":{
    "phone":"0123456789",
    "colour":"black"
  }
}

Json B =>
    {
      "customer": {
        "fullName": "Sammy J",
        "age": 31,
        "year":1985,
        "address":{
            "lineTwo":"lineTwo",
            "lineOne":"lineOne"
        }
    },
      "handset":{
        "colour":"red",
        "phone":"0123456788"
      }
    }

I want compare these two json and it should return true as keys are matching and both json structure is same.我想比较这两个 json,它应该返回 true,因为键匹配并且两个 json 结构相同。 So is there a clean way of doing it?那么有没有一种干净的方法呢?

I know using Gson lib I can compare two JsonElement but that would match values as well which I don't want to keep as constraint for my use-case.我知道使用 Gson lib 我可以比较两个 JsonElement 但这也会匹配我不想保留作为我的用例的约束的值。

JsonParser parser = new JsonParser();
JsonElement p1 = parser.parse(JsonA);
JsonElement p2 = parser.parse(JsonB);
System.out.printf(p1.equals(p2) ? "Equal" : "Not Equal"); //it returns true if values are same.

This is indeed a case for JSON Schema validation, refer Core and Validation .这确实是 JSON Schema 验证的情况,请参阅CoreValidation

There are a few JSON schema validators available, for the below examples, I am using enter link description here .有一些 JSON 模式验证器可用,对于下面的示例,我在此处使用输入链接描述 The library binaries are available in Maven, it can also be downloaded (along with all dependency and javadoc) from here .库二进制文件在 Maven 中可用,也可以从这里下载(以及所有依赖项和 javadoc)。 Other validators are also available from here .其他验证器也可以从这里获得

It would perhaps be of help to go throughthis guide .阅读本指南可能会有所帮助。

The schema for the example is as below (SampleJsonSchema.json):该示例的架构如下(SampleJsonSchema.json):

{
    "$schema":"http://json-schema.org/draft-07/schema#",
    "id":"http://test.org/sampleJsonSchema1",
    
    "title":"SampleJSONSchema",
    
    "description":"This is the description",
    
    "type":"object",
    
    "properties":{
    
        "customer":{
        
            "type":"object",
            "properties":{
            
                "fullname":{"type":"string"},
                "age":{"type":"integer"},
                "year":{"type":"integer"},
                "address":{
            
                    "type":"object",
                    "properties":{
                    
                        "lineOne":{"type":"string"},
                        "lineTwo":{"type":"string"}
                    
                    },
                    
                    "required":["lineOne", "lineTwo"],
                    "maxProperties":2

                }
            
            },
            
            "required":["fullname","age","year","address"],
            "maxProperties":4   
        
        },
        
        "handset":{
        
            "type":"object",
            "properties":{
            
                "phone":{"type":"string"},
                "colour":{"type":"string"}
            
            },
            
            "required":["phone","colour"],
            "maxProperties":2
        
        }
    
    }
}

The data used is as below (SampleJsonData.json:使用的数据如下(SampleJsonData.json:

{
  "customer": {
  
   "fullname": "Emily Jenkins",
    "age": 29,
    "year":1988,

    "address":{
    
        "lineOne":"lineOne",
        "lineTwo":"lineTwo"
    }
},
  "handset":{
    "phone":"0123456789",
    "colour":"black"
  }
}

The validation routine is as below:验证程序如下:

package org.test;包 org.test;

import java.io.File;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;

public class JsonValidation {

    public static void main(String[] args) throws Exception{
        
        
        String jsonSchemaPath="F:\\workspaces\\utilities\\TestJava\\jsonSchema\\SampleJsonSchema.json";
        String jsonDataPath="F:\\workspaces\\utilities\\TestJava\\jsonSchema\\SampleJsonData.json";
        
        ObjectMapper mapper=new ObjectMapper();
        
        JsonNode schemaNode=mapper.readValue(new File(jsonSchemaPath), JsonNode.class);
        JsonNode dataNode=mapper.readValue(new File(jsonDataPath), JsonNode.class);
        
        JsonSchema jsonSchema=JsonSchemaFactory.byDefault().getJsonSchema(schemaNode);
        
        ProcessingReport validationReport=jsonSchema.validate(dataNode);
        
        System.out.println(validationReport.toString());

    }//main closing

}//class closing

A number of tests can be run by changing the schema and the data to observe different results.可以通过更改架构和数据来运行许多测试以观察不同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java - 以不同的顺序比较两个具有相同键的json对象 - java - Compare two json objects with same keys in different order 如何断言两个 JSON 对象在 JSON 数组中具有相同的键但值不同 - How to assert two JSON objects which have the same keys but different in values inside of a JSON array 比较具有相同键的两个Json对象并推入数组-Java - Compare two Json objects with same keys and push into array- java 如何合并两个具有相同键的嵌套映射并保留值 - How to merge two nested maps with same keys and keep the values 通过键比较两个哈希图,并返回不具有相同频率的返回键 - Compare two hashmaps by keys and return keys which do not have same frequencies 如何在相同标签中比较两个具有不同属性值的xml - how to compare two xml with different attribute values in same tags 无论如何在Java HashMap中有两个相同的键,但是值不同? - Anyway to have two of the same keys, but different values in Java HashMap? hashmap 中具有不同键的相同值 - Same values with different keys in a hashmap 我有两个 hashmap HashMap <string,list<string> &gt; 在这种格式下,如何比较两个值是否相同或不同的键</string,list<string> - I have two hashmap HashMap<String,List<String>> in this format how to compare both the values are same or not with same keys 比较两个具有相同结构的文件 - compare two file that have same structure
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM