gpt4 book ai didi

java - Gson如何排除JsonSerializer中的某些字段

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

我只需要更改一个字段,另一个字段我想要有默认值,但使用此代码我在输出中只有一个字段 - 我在 JsonSerializer 中编写的字段,但我需要拥有所有字段并且只有一个字段为了改变。有一个属性方法可以做到这一点吗?

GsonBuilder gson = new GsonBuilder().serializeNulls();
gson.registerTypeAdapter(TripCardView.class, new JsonSerializer<TripCardView>() {
@Override
public JsonElement serialize(TripCardView src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jObj = new JsonObject();
jObj.add("numberShortYear", new JsonPrimitive(src.getNumberShortYear()));
return jObj;
}
});
jsonResponse.add("aaData", gson.setDateFormat("dd.MM.yyyy").create().toJsonTree(result));

最佳答案

只有一些小改动,请参阅下面代码中的注释:

gson.registerTypeAdapter(TripCardView.class, new JsonSerializer<TripCardView>() {
// You need to create a new Gson in your serializer because calling original contex
// would call this serializer again and cause stack overflow because of recursion
private Gson gson = new GsonBuilder().setDateFormat("dd.MM.yyyy").create();
@Override
public JsonElement serialize(TripCardView src, Type typeOfSrc,
JsonSerializationContext context) {
// You need to serialize the original object to have its fields populated 'default'
JsonElement result = gson.toJsonTree(src);
// After that it is just to add the extra field with value from method call
result.getAsJsonObject().add("numberShortYear",
new JsonPrimitive(src.getNumberShortYear()));
return result;
}
});

关于java - Gson如何排除JsonSerializer中的某些字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59389760/

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