GSON 输出空数组值
GSON outputs null array values
这是我的 GSON 实例,因为您看不到 serializeNulls()。
private static final Gson GSON = new GsonBuilder().create();
这就是我生成 json:
的方式
object.add("inventory", GSON.toJsonTree(inventory.getItems()));
项目:
private int id;
private int amount;
public Item(int id, int amount) {
this.id = id;
this.amount = amount;
}
输出:
"inventory": [
{
"id": 13
"amount": 1,
},
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
],
我也试过创建一个适配器,但没有成功:
@Override
public JsonElement serialize(Item src, Type typeOfSrc, JsonSerializationContext context) {
System.out.println(src); // This only prints valid values, no nulls...
return new Gson().toJsonTree(src, src.getClass());
}
为什么输出包含空值,我该如何去除这些空值?
您可以像这样编写自定义 JSON 序列化程序适配器:
public class CustomJsonArraySerializer<T> implements JsonSerializer<T[]> {
@Override
public JsonElement serialize(T[] source, Type type, JsonSerializationContext context) {
JsonArray jsonArray = new JsonArray();
for(T item : source){
if(item != null) { // skip null values
jsonArray.add(context.serialize(item));
}
}
return jsonArray;
}
}
您可以像这样注册这个自定义序列化程序采用者:
private static final Gson GSON = new GsonBuilder().registerTypeAdapter(Item[].class, new CustomJsonArraySerializer<>()).create();
现在,当您序列化 Item[]
时,它将忽略 null
值。
测试:
Item[] items = {new Item(10, 20), null, null, null, new Item(50, 60)};
JsonElement jsonElement = GSON.toJsonTree(items);
System.out.println(jsonElement);
输出:
[{"id":10,"amount":20},{"id":50,"amount":60}]
这是我的 GSON 实例,因为您看不到 serializeNulls()。
private static final Gson GSON = new GsonBuilder().create();
这就是我生成 json:
的方式object.add("inventory", GSON.toJsonTree(inventory.getItems()));
项目:
private int id;
private int amount;
public Item(int id, int amount) {
this.id = id;
this.amount = amount;
}
输出:
"inventory": [
{
"id": 13
"amount": 1,
},
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
],
我也试过创建一个适配器,但没有成功:
@Override
public JsonElement serialize(Item src, Type typeOfSrc, JsonSerializationContext context) {
System.out.println(src); // This only prints valid values, no nulls...
return new Gson().toJsonTree(src, src.getClass());
}
为什么输出包含空值,我该如何去除这些空值?
您可以像这样编写自定义 JSON 序列化程序适配器:
public class CustomJsonArraySerializer<T> implements JsonSerializer<T[]> {
@Override
public JsonElement serialize(T[] source, Type type, JsonSerializationContext context) {
JsonArray jsonArray = new JsonArray();
for(T item : source){
if(item != null) { // skip null values
jsonArray.add(context.serialize(item));
}
}
return jsonArray;
}
}
您可以像这样注册这个自定义序列化程序采用者:
private static final Gson GSON = new GsonBuilder().registerTypeAdapter(Item[].class, new CustomJsonArraySerializer<>()).create();
现在,当您序列化 Item[]
时,它将忽略 null
值。
测试:
Item[] items = {new Item(10, 20), null, null, null, new Item(50, 60)};
JsonElement jsonElement = GSON.toJsonTree(items);
System.out.println(jsonElement);
输出:
[{"id":10,"amount":20},{"id":50,"amount":60}]