我正在尝试使用空值反序列化我自己的类。但是我的代码不起作用。
我的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/