java - 从 json 到 json 立即崩溃

标签 java json gson android

以下代码段因 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/

相关文章:

MySQL JSON - 如何在匹配路径的所有元素上使用 JSON_SET?

java - 从字符串数组列表中获取删除和添加的元素

java群发邮件发件人

java - 解耦 JSON 服务中 unicode 转义导致的安全漏洞?

arrays - JQ - 合并两个数组

java - 如何修复日期转换时的 'JsonSyntaxException'

java - 什么是泛型方法,在这种情况下 <T> 是如何绑定(bind)的?

java - 当值不在环境文件中时 spring 属性文件的行为

java - fromJson 引发无法解析的日期异常

java - MalformedJsonException : Use JsonReader. setLenient(true) 接受格式错误的 JSON - Android Studio