String转json,多层json解析,并使用JsonElement对比两个json对象的值是否相等
Posted 近朱朱者赤
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了String转json,多层json解析,并使用JsonElement对比两个json对象的值是否相等相关的知识,希望对你有一定的参考价值。
导入需要的jar包:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
示例:
public 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 < rightAnswerJsonArray.size(); i ++) {
boolean flag = false;
JsonArray answerJsonArray = answerElement.getAsJsonArray();
for (int j = 0; j < answerJsonArray.size(); j ++) {
if (JsonTest.test(answerElement.getAsJsonArray().get(j), rightAnswerJsonArray.get(i))) {
flag = true;
break;
}
}
if (!flag) {
return false;
}
}
} else {
return false;
}
} else if (rightAnswerElement.isJsonObject()) {
JsonObject rightAnswerJsonObject = rightAnswerElement.getAsJsonObject();
Set<String> 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对象的值是否相等的主要内容,如果未能解决你的问题,请参考以下文章