以下代码段因 Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
String jsonObjString = gson.toJson(customClassInstance, MyCustomClass.class);
gson.fromJson(jsonObjString, MyCustomClass.class); // Crashes here
为什么?当我打印 jsonObjString
时,它看起来很好。
并且编码/解码似乎是正确的。问题是什么?
更新:
public class MyCustomClass {
@SerializedName(“customer_city”)
private String customerCity;
@SerializedName(“customer_id”)
private String customerId;
private LocalDate entry;
@SerializedName(“customer_income”)
private double customerIncome;
private String[] cards;
@SerializedName(“customer_name")
private String customerName;
}
最佳答案
您的 LocalDate
需要一种确定的序列化和反序列化方式。为此,您必须在 Gson
实例中注册自定义类型适配器。
public class LocalDateAdapter extends TypeAdapter<LocalDate> {
public LocalDate read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
String xy = reader.nextString();
return new LocalDate(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(xy);
}
public void write(JsonWriter writer, LocalDate value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
String xy = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(value.getTime());
writer.value(xy);
}
}
你需要这样的东西,虽然我不太确定 LocalDate
的 API。
然后注册到你的Gson实例
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
.create();
关于java - 从 json 到 json 立即崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36737047/