gpt4 book ai didi

java - 复杂的 Json 对象到带有 Gson 的 Map 字段的 Java 对象

转载 作者:行者123 更新时间:2023-12-02 04:25:20 25 4
gpt4 key购买 nike

我有一个像这样的 Json 结构:

{
"Pojo" : {
"properties" : {
"key0" : "value0",
"key1" : "value1"
}
}
}

我希望我的最终结果看起来像这样:

public class Pojo {
public Map<String, String> properties;
}

但我得到的是这样的东西:

public class Pojo {
public Properties properties;
}

public class Properties {
public String key0;
public String key1;
}

现在我为解析 Json 所做的就是这样:

new Gson().fromJson(result, Pojo.class)

想一下我需要做什么才能正确设置此设置?我没有能力更改 Json 返回对象的结构。

最佳答案

Gson 正在尝试将 JSON 字段名称与 POJO 字段相匹配,因此上面的 JSON 暗示顶级对象有一个名为“Pojo”的字段。其实就是表示如下的类结构,

class Container {
MyObject Pojo;
}

class MyObject {
Map<String, String> properties;
}

其中类 MyObjectContainer 的名称完全是任意的。 Gson 匹配字段名称,而不是对象类型名称。

您可以使用简单的语句反序列化该对象 -

Container container = gson.fromJson(result, Container.class);

您的 map 将是container.Pojo.properties

如果您不想拥有额外的容器类,您可以先解析为 Json 树,然后再添加您感兴趣的部分 --

JsonElement json = new JsonParser().parse(result);
// Note "Pojo" below is the name of the field in the JSON, the name
// of the class is not important
JsonElement pojoElement = json.getAsJsonObject().get("Pojo");
Pojo pojo = gson.fromJson(pojoElement, Pojo.class);

那么你的 map 就在 pojo.properties 中,我想这就是你想要的。为了清楚起见,我省略了错误检查,但您可能需要添加一些错误检查。

关于java - 复杂的 Json 对象到带有 Gson 的 Map 字段的 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32260787/

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