gson不会反序列化数组

时间:2016-05-12 13:22:35

标签: java serialization gson

拥有以下json字符串:

[{"Custom":{"id":4,"name":"Lebensmittel","currency":"EUR","count":2}}]

这是一个缩短版本,通常我有一个很长的json字符串,有很多“自定义”对象。 我从一台我没有影响力的远程机器上收到json String。 我正在尝试使用以下代码反序列化json String:

Gson gson = new Gson();
Custom[] data = gson.fromJson(json, custom[].class);

结果是Array数据的大小是正确的,但是内容为null,没有反序列化的值。

这是POJO类Custom

public class Custom implements Serializable {

private static final long serialVersionUID = 1826747252056159012L;

private int id;

private String name;

private String currency;

private int count;

public Custom() {
}

public int getId() {
    return id;
}

public void setId(final int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(final String name) {
    this.name = name;
}

public String getCurrency() {
    return currency;
}

public void setCurrency(final String currency) {
    this.currency = currency;
}

public int getCount() {
    return count;
}

public void setCount(final int count) {
    this.count = count;
}

}

那么,有谁能告诉我什么是wrog?

提前举手

2 个答案:

答案 0 :(得分:2)

你的json有错误:

[{"Custom":{"id":4,"name":"Lebensmittel","currency":"EUR","count":2}}]

必须是

[{"id":4,"name":"Lebensmittel","currency":"EUR","count":2}]

答案 1 :(得分:0)

您可以使用自定义TypeAdapter(或JsonDeserializer,如果您不需要序列化)

private static class CustomTypeAdapter  extends TypeAdapter<Custom>{
    private static final Gson gson = new Gson();
    @Override
    public void write(JsonWriter out, Custom value) throws IOException {
        if (value!= null)
         out.beginObject()
                 .name("Custom")
                 .jsonValue(gson.toJson(value))
                 .endObject();
    }

    @Override
    public Custom read(JsonReader in) throws IOException {
        Custom custom = null;
        in.beginObject();
        String name = in.nextName();
        if (name.equals("Custom")) {
            custom = gson.fromJson(in, Custom.class);
        }
        in.endObject();
        return custom;
    }
}

并按照以下方式注册:

Gson gson = new GsonBuilder()
             .registerTypeAdapter(Custom.class, new CustomTypeAdapter())
             .create();
Custom[] data = gson.fromJson(json, Custom[].class);

其他选项是使用这样的自定义包装:

public static class CustomWrapper{
    @SerializedName("Custom")
    public Custom custom;
}

用例:

CustomWrapper[] data = gson.fromJson(json, CustomWrapper[].class);