android - 使用 gson 和 null 值反序列化

标签 android gson

我正在尝试使用空值反序列化我自己的类。但是我的代码不起作用。

我的JSON:

{"Text":null,"Code":0,"Title":"This is Sparta!"}

在我的方法中,我执行以下操作:

this.setText(gson.fromJson(jsonObject.getString("Text"), String.class));
this.setTitle(gson.fromJson(jsonObject.getString("Title"), String.class));
this.setCode(gson.fromJson(jsonObject.getString("Faccode"), Integer.class))

我没有反序列化整个对象,因为可以有一个 List<T> ,也是。

错误:

myapp W/System.err? com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 6 path $
myapp W/System.err? at com.google.gson.Gson.assertFullConsumption(Gson.java:786)
myapp W/System.err? at com.google.gson.Gson.fromJson(Gson.java:776)
myapp W/System.err? at com.google.gson.Gson.fromJson(Gson.java:724)
myapp W/System.err? at com.google.gson.Gson.fromJson(Gson.java:696)

最佳答案

首先,您必须了解如何使用 gson 进行解析。你可以找到一些例子 here .

现在你知道如何解析了,你仍然会遇到 null 值的问题。要解决它,您必须告诉 gson 使用

(反)序列化 null
Gson gson = new GsonBuilder().serializeNulls().create();

来自 serializeNulls() doc

Configure Gson to serialize null fields. By default, Gson omits all fields that are null during serialization.

编辑(未测试,基于文档)

为了获得一些独特的值(value),你可以这样做

String json = ""; //Your json has a String
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();

//If null, use a default value
JsonElement nullableText = jsonObject.get("Text");
String text = (nullableText instanceof JsonNull) ? "" : nullableText.getAsString();

String title = jsonObject.get("Title").toString();
int code = jsonObject.get("Code").getAsInt();

否则如果你有这个pojo

public class MyElement {
    @SerializedName("Text")
    private String text;

    @SerializedName("Title")
    private String title;

    @SerializedName("Code")
    private int code;
}

你可以使用

String json = ""; //Your json has a String
Gson gson = new GsonBuilder().serializeNulls().create();
MyElement myElement = gson.fromJson(json, MyElement.class);

关于android - 使用 gson 和 null 值反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33435683/

相关文章:

java - Android Studio – 运行测试时执行哪个 .java 文件?

android - Android 上的 OpenGL ES 坐标系?

java - 在 Intellij Idea 13 中呈现为包的目录?

java - 如何使用 gson 调用默认反序列化

java - 在 Java 中同时处理 Json 数组并按顺序处理

java - gson.JsonObject 和类加载造成非常奇怪的情况

android - 可以使用 TLS v1.2 打开网页的第 3 方 Android WebView

android - 我的服务器如何使用 Google 帐户对 Android 用户进行身份验证?

java - 如何使用 GSON 命名 JSON 对象数组?

android - 使用 gson 库将自定义对象的 ArrayList 转换为 JSON,检索这些自定义对象时出现 ClassCastException