String转json,多层json解析,并使用JsonElement对比两个json对象的值是否相等
2021-03-07 12:29
标签:one 数组类 test 需要 dep 导入 artifact str stat 导入需要的jar包: 示例: String转json,多层json解析,并使用JsonElement对比两个json对象的值是否相等 标签:one 数组类 test 需要 dep 导入 artifact str stat 原文地址:https://www.cnblogs.com/zys-blog/p/12886666.htmlpublic class JsonTest {
public static void main(String[] args) {
String rightAnswer = "{\"unit\":\"单位\",\"year\":\"2018\",\"form\":[{\"subject\":\"数学\",\"summary\":[11,12,13],\"score\":\"88.00\"},{\"subject\":\"语文\",\"summary\":[13,11],\"score\":\"99.00\"},{\"subject\":\"化学\",\"summary\":[],\"score\":\"77.00\"},{\"subject\":\"政治\",\"summary\":[1],\"score\":\"100.00\"}],\"people\":\"花花\"}";
String answer = "{\"unit\":\"单位\",\"year\":\"2018\",\"form\":[{\"subject\":\"数学\",\"summary\":[11,12,13],\"score\":\"88.00\"},{\"subject\":\"语文\",\"summary\":[13,11],\"score\":\"99.00\"},{\"subject\":\"化学\",\"summary\":[],\"score\":\"77.00\"},{\"subject\":\"政治\",\"summary\":[1],\"score\":\"100.00\"}],\"people\":\"草草\"}";
String a = "{\"error\":[10,14],\"imgId\":[1]}";
String b = "{\"error\":[14,10],\"imgId\":[]}";
JsonParser jsonParser = new JsonParser();
System.out.println("=====" + JsonTest.test(jsonParser.parse(answer), jsonParser.parse(rightAnswer)));
}
public static Boolean test(JsonElement answerElement, JsonElement rightAnswerElement) {
if (rightAnswerElement.isJsonArray()) {
JsonArray rightAnswerJsonArray = rightAnswerElement.getAsJsonArray();
if (rightAnswerJsonArray.size() == answerElement.getAsJsonArray().size()) {
//数组类型顺序会影响取值,所以每个数组都要全部匹配验证另外一个对象的数组。
//例如:[10,14]和[14,10]
for (int i = 0; i keys = rightAnswerJsonObject.keySet();
for (String key : keys) {
if(!JsonTest.test(answerElement.getAsJsonObject().get(key), rightAnswerJsonObject.get(key))) {
return false;
}
}
} else if (rightAnswerElement.isJsonPrimitive()) {
String rightAnswer = rightAnswerElement.getAsString();
String answer = answerElement.getAsString();
System.out.println("rightAnswer = " + rightAnswer + ", answer = " + answer);
if (!rightAnswer.equals(answer)) {
return false;
}
}
return true;
}
}
文章标题:String转json,多层json解析,并使用JsonElement对比两个json对象的值是否相等
文章链接:http://soscw.com/index.php/essay/61339.html