gpt4 book ai didi

java - Gson 嵌套对象

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

我正在使用带有类的库来映射 json 消息,并使用 Gson 通过 json 序列化类。该消息包含数据字段。该字段是通用的,它包含任何内容。库提供的类是:

public class Api {
....
@SerializedName("data")
Map<String, JsonElement> data;
....
}

现在我想扩展该类,但我有自己的根对象来映射数据子字段,因此要做一个总结,json 类似于:

{...., "data": {"myownroot":"aaaa"}}

我该怎么办?我当然可以创建自己的类,但如果可能的话,我更愿意扩展库。如果我延长类(class),我会:

public class MyOwnRoot extends Api {
@SerializedName("myownroot")
public String root;
}

但在这种情况下,当我序列化时它不起作用,因为 myownroot 必须是 data 的子级,但我怎么能对 Gson 说“将 MyOwnRoot 放入数据映射中”??

最佳答案

我真的不明白为什么你需要扩展 Api 类。我想这个类名有点用词不当,因为 API(一般来说)是接口(interface),并且它们得到了实现。

我想你可以通过使用 getter 来实现这一点,同时让 Gson 在字段上完成工作。

编辑:也要序列化

public class Api {
@SerializedName("data")
protected Map<String, JsonElement> data;
}

public class RootEntity extends Api {
transient StructuredRootImpl _cached;
transient Gson _gson = new Gson();

public class StructuredRootImpl {
Integer v;
String name;
}

public Integer getV() {
synch();
return _cached.v;
}

public void setV(Integer v) {
_cached.v=v;
synch();
}

private void synch() {
if(_cached==null){
if(data==null){
data = new LinkedHashMap<>();
}
JsonElement jsonElement = data.get("myroot");
_cached = _gson.fromJson(jsonElement, StructuredRootImpl.class);
}
JsonElement jsonTree = _gson.toJsonTree(_cached);
data.put("myroot", jsonTree);
}

public String getName() {
synch();
return _cached.name;
}

public void setName(String name) {
_cached.name = name;
synch();
}

@Override
public String toString() {
return "RootEntity [v=" + getV() + ", n=" + getName() + "]";
}

}

运行主程序,您可以序列化和反序列化您的实体。

public class TestGson {

public static void main(String[] args) {
String jsonText = "{data:{\"myroot\":{\"v\":123,\"name\":\"mario\"}}}";
Gson gson = new Gson();
RootEntity entity = gson.fromJson(jsonText, RootEntity.class);
System.out.println(entity);
entity.setName("Alex");
entity.setV(150);
String thenBack = gson.toJson(entity);
System.out.println(thenBack);

}
}

这将导致:

so.alpha.TestGson$Foo@4b85612c
StructuredRoot [v=123, name=mario]

我还是不明白为什么你要扩展 Api 类。

关于java - Gson 嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44418744/

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