gpt4 book ai didi

java - 在java中解析递归未知的json输入结构

转载 作者:行者123 更新时间:2023-11-30 06:20:14 26 4
gpt4 key购买 nike

我正尝试在 java 中解析递归未知的 json 输入结构,如下面的格式,并尝试在另一个 json 中重写相同的结构。

同时,我需要在解析时验证每个 json 键/值。

{"Verbs":[{
"aaaa":"30d", "type":"ed", "rel":1.0, "id":"80", "spoken":"en", "ct":"on", "sps":null
},{
"aaaa":"31", "type":"cc", "rel":3.0, "id":"10", "spoken":"en", "ct":"off", "sps":null
},{
"aaaa":"81", "type":"nn", "rel":3.0, "id":"60", "spoken":"en", "ct":"on", "sps":null
}]}

请建议我可以使用哪个 json 解析器来读取和写入未知的 json 内容。

最佳答案

这样你就可以递归解析 JSON 对象:

import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;

public class JsonQuestion {

public static void main(String[] args) {
String input = "{\"Verbs\":[{\n" +
" \"aaaa\":\"30d\", \"type\":\"ed\", \"rel\":1.0, \"id\":\"80\", \"spoken\":\"en\", \"ct\":\"on\", \"sps\":null\n" +
"},{\n" +
" \"aaaa\":\"31\", \"type\":\"cc\", \"rel\":3.0, \"id\":\"10\", \"spoken\":\"en\", \"ct\":\"off\", \"sps\":null\n" +
"},{\n" +
" \"aaaa\":\"81\", \"type\":\"nn\", \"rel\":3.0, \"id\":\"60\", \"spoken\":\"en\", \"ct\":\"on\", \"sps\":null\n" +
"}]}";

JsonObject jsonObject = JsonObject.readFrom(input);
handleObject(jsonObject);
}

private static void handleValue(JsonObject.Member member, JsonValue value) {
if (value.isArray()) {
if (member != null) {
System.out.print("name = " + member.getName());
}
System.out.println("array value ");
recurseArray(value.asArray());
} else if (value.isBoolean()) {
if (member != null) {
System.out.print("name = " + member.getName());
}
System.out.println(", boolean value = " + value.asBoolean());
} else if (value.isNull()) {
if (member != null) {
System.out.print("name = " + member.getName());
}
System.out.println(", null value");
} else if (value.isNumber()) {
if (member != null) {
System.out.print("name = " + member.getName());
}
System.out.println(", number value = " + value.asDouble());
} else if (value.isObject()) {
if (member != null) {
System.out.print("name = " + member.getName());
}
System.out.println(", object value ");
handleObject(value.asObject());
} else if (value.isString()) {
if (member != null) {
System.out.print("name = " + member.getName());
}
System.out.println(", string value = " + value.asString());
}
}

private static void handleObject(JsonObject object) {
for (JsonObject.Member next : object) {
JsonValue value = next.getValue();
handleValue(next, value);
}
}

private static void recurseArray(JsonArray array) {
for (JsonValue value : array) {
handleValue(null, value);
}
}
}

关于java - 在java中解析递归未知的json输入结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22111857/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com