Jim
Jim

Reputation: 19582

To json from json crashes immediately

The following snippet crashes with 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

Why? When I print the jsonObjString it seems fine.
And the encoding/decoding seems correct. What is the problem?

Update:

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;

}

Upvotes: 1

Views: 511

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81549

Your LocalDate requires a deterministic way of serializing and deserializing it. For that, you have to register a custom type adapter in your Gson instance.

   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);
     }
   }

You need something like that, although I'm not exactly sure about the API of LocalDate.

Then register it to your Gson instance

Gson gson = new GsonBuilder()
     .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
     .create();

Upvotes: 1

Related Questions