【问题标题】:How could I works with Gson when JSON returns Null?当 JSON 返回 Null 时,我如何使用 Gson?
【发布时间】:2015-01-21 17:24:21
【问题描述】:

我有一个 JSON,它返回一些值为“null”的对象。我正在尝试这个值并使用 Gson 添加到我的对象类中。问题是当这个值等于 null 时,我不能这样做,因为会引发异常“NullPointerException”。如果 JSON 对象没有 null 值,我可以工作,但如果有 null 值,我不能

我怎么能用空值做到这一点?

JSON

"Cotacao": {
   "endereco": null,
   "bairro": null,
   "cidade": null      
}

类对象

public class Cotacao implements Serializable {
    private static final long serialVersionUID = 1L;

    private String endereco;
    private String bairro;
    private String cidade;
    //gets sets

获取 GSON 值

Gson gson = new Gson();
JSONObject jsoCotacao = jsoObj.getJSONObject("Cotacao");
Cotacao cotacao = gson.fromJson(jsoCotacao.toString(), Cotacao.class);

【问题讨论】:

  • jsoObj 是什么,getJSONObject 有什么作用?能发下相关代码吗?

标签: json gson


【解决方案1】:

我解决了这个问题。

我做到了

public class GsonNullObject<T> implements TypeAdapterFactory {
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

        Class<T> rawType = (Class<T>) type.getRawType();
        if (rawType != String.class) {
            return null;
        }
        return (TypeAdapter<T>) new StringAdapter();
    }
}


public class StringAdapter extends TypeAdapter<String> {
    public String read(JsonReader reader) throws IOException {
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return "";
        }
        return reader.nextString();
    }
    public void write(JsonWriter writer, String value) throws IOException {
        if (value == null) {
            writer.nullValue();
            return;
        }
        writer.value(value);
    }
}

使用

Gson gson = new GsonBuilder().registerTypeAdapterFactory(new GsonNullObject<Cotacao>()).create();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    相关资源
    最近更新 更多