想要在json路径的帮助下比较两个json对象,它们的结构是否相同。我不考虑值,只考虑结构。提前感谢您的帮助 例如下面两个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 对象获取 key 并比较两者。想验证我的逻辑是否正确。
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;
}
最佳答案
如果结构一致,您可以做的一件事就是尝试通过将这些 JSON 对象映射到类来转换它们。如果它发现任何其他不存在的键,它将引发异常,并且通过捕获它,您知道它们具有不同的结构。默认情况下启用此功能,可以使用注释 @JsonIgnoreProperties(ignoreUnknown = true)
禁用它并进行尝试。
实现此目的的一个好方法是添加 Jackson 库 this is a good link tutorial并执行以下操作:
class Foo {
@JsonProperty("squadName") String name;
// (other props...)
}
关于java - 如何使用java相对于json路径等于或不等于两个json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52429024/