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

两盒软妹~` 提交于 2021-02-11 15:01:29

问题


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. 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.

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.

回答1:


This is indeed a case for JSON Schema validation, refer Core and Validation.

There are a few JSON schema validators available, for the below examples, I am using enter link description here . The library binaries are available in Maven, it can also be downloaded (along with all dependency and javadoc) from here . Other validators are also available from here.

It would perhaps be of help to go through this guide.

The schema for the example is as below (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:

{
  "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;

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.



来源:https://stackoverflow.com/questions/64736965/compare-two-json-which-has-same-nested-structure-and-same-keys-but-values-can-be

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!