gpt4 book ai didi

java - 使用 GSON 解析类

转载 作者:行者123 更新时间:2023-11-30 10:23:14 24 4
gpt4 key购买 nike

我正在尝试使用 GSON 解析特定的 JSON 文件。到目前为止,它运行良好,因为我处理的所有 JSON 都具有数据属性。

但我偶然发现了这个数据结构,根据 Stack Overflow 上的其他一些问题,这似乎有问题。

"custom" 字段是完全随机的,本示例只使用一个,但可以有尽可能多的字段。 “条件”、“ Action ”、“表达式”是固定字段,其余部分也是固定字段,但为了这个问题,我没有包括其余的解析。

JSON 文件:

{
"custom": {
"conditions": [
{
"id": "is-large-number",
"scriptName": "IsLargeNumber",
"highlight": true,
"params": [
{
"id": "number",
"type": "number"
}
]
}
],
"actions": [
{
"id": "do-alert",
"scriptName": "Alert",
"highlight": true
}
],
"expressions": [
{
"id": "double",
"expressionName": "Double",
"scriptName": "Double",
"highlight": true,
"returnType": "number",
"params": [
{
"id": "number",
"type": "number"
}
]
}
]
}
}

我需要将其解析为我自己的类。解析成 java Object 就像一个魅力,但我需要在将数据转储回新的 JSON 文件之前修改数据,因此使用我自己的类。

所以我开始创建自己的序列化程序:

public class ACESDeserializer implements JsonDeserializer<JSONACEs>{
public JSONACEs deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Map<String, JSONACEsCategory> nodes = new HashMap<>();
JsonObject categories = json.getAsJsonObject();
for (Map.Entry<String, JsonElement> category : categories.entrySet()) {
String categoryName = category.getKey();
JsonElement categoryData = category.getValue();
JSONACEsCategory node = context.deserialize(categoryData, JSONACEsCategory.class);
nodes.put(categoryName, node);
}
return new JSONACEs(nodes);
// https://stackoverflow.com/questions/10668452/parsing-a-json-file-with-gson
}
}

加载是这样的:

private void loadACESJSON() {
final GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(JSONACEs.class, new ACESDeserializer());
final Gson gson = builder.setPrettyPrinting().create();
try {
final JsonReader reader = new JsonReader(new FileReader("src/main/resources/c3-plugin-sdk-v1/aces.json"));
_JSONACEs = gson.fromJson(reader, JSONACEs.class);
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println(gson.toJson(_JSONACEs));
}

这是我的“容器”类,JSONACE,带有一张 map ,因为“自定义”字段是随机的:

public class JSONACEs {
private Map<String, JSONACEsCategory> _categories;

public JSONACEs(Map<String, JSONACEsCategory> nodes) {
_categories = nodes;
}
}

这是对象本身,JSONACEsCategory,它是空的,因为我无法让第一部分工作:

public class JSONACEsCategory {

}

运行这个应用输出:

{
"_categories": {
"custom": {}
}
}

应该在哪里输出

{
"custom": {}
}

如您所见,"_categories" 被转储了,这是错误的。它应该将 "custom" 直接转储为主要 JSON 对象的子对象。

编辑

在 JSONSACEs 中为 map 添加了一个 getter 并将其输出到控制台返回:

{custom=com.psycho.c3plugen.model.JSONACEsCategory@25733d8}

所以从技术上讲,它看起来还不错。所以我的猜测是我还需要编写自己的序列化程序吗?任何人都可以解释我将如何做到这一点才能正确输出?

最佳答案

正如 RC 在评论中指出的那样,解决方案非常简单:

使用简单序列化

gson.toJson(_JSONACEs.getCategories());

代替

gson.toJson(_JSONACEs);

关于java - 使用 GSON 解析类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47134527/

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