我想比较两个json对象,在json路径的帮助下,它们在结构上是否相同。我不考虑值,只是提前structure.Thank你有任何帮助例如下面两个json文件json-1和json-2,两者在结构上是相同的,但你可以看到值是不同的。
json-1
{
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "man1",
"age": 50,
"secretIdentity": "Dan",
"powers": [
"Radiation resistance",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
}
]
}
json-2
{
"squadName": "Super hero1",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Man2",
"age": 33,
"secretIdentity": "Jukes",
"powers": [
"Radiation resistance",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut1111",
"age": 30,
"secretIdentity": "ran",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
}
]
}
下面两个json具有不同的结构:
{
"squadName": "Super hero1",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Man2",
"age": 33,
"secretIdentity": "Jukes",
"powers": [
"Radiation resistance",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut1111",
"age": 30,
"secretIdentity": "ran",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
}
]
}
and
{
"Name": "Super hero1",
"Town": "Metro City",
"year": 2016,
"base": "Super tower",
"IsActive": true,
"associates": [
{
"name1": "Man2",
"age1": 33,
"secretIdentity1": "Jukes",
"powers1": [
"Radiation resistance",
"Turning tiny",
"Radiation blast"
]
},
{
"name1": "Madame Uppercut1111",
"age1": 30,
"secretIdentity1": "ran",
"powers1": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
}
]
我已经编写了前面提到的来自两个json对象的below.Getting键的代码,并通过比较both.Wanted来验证我的逻辑是否正确。
List<String>list4 =printJsonObject(obj);
List<String>list5 =printJsonObject(obj1);
if(list5.containsAll(list4)){
boolean res=true;
System.out.println("res"+res);
}
public static List printJsonObject(JSONObject jsonObj) throws
JSONException {
Iterator keys = jsonObj.keys();
List<String> jsonKeys=new ArrayList<String>();
while(keys.hasNext()){
//based on you key types
Object keyObj = (String)keys.next();
Object keyvalue = jsonObj.get(keyObj.toString());
jsonKeys.add(keyObj.toString());
//for nested objects iteration if required
if (keyvalue instanceof JSONObject)
printJsonObject((JSONObject)keyvalue);
}
return jsonKeys;
}
发布于 2018-09-21 00:12:51
如果结构是一致的,您可以做的一件事是尝试通过将这些JSON对象映射到类来转换它们。如果它发现任何其他键不存在,它将引发异常,并通过捕获它,您知道它们具有不同的结构。这在默认情况下是启用的,可以使用注释@JsonIgnoreProperties(ignoreUnknown = true)
禁用它,并尝试使用它。
这样做的一个好方法是添加Jackson库this is a good link tutorial并执行以下操作:
class Foo {
@JsonProperty("squadName") String name;
// (other props...)
}
https://stackoverflow.com/questions/52429024
复制相似问题