3

I have a a JSON string as :

{
    "personId": "person1",
    "userId": "user1"
    "details": [
        {
            "homeId": "home1",
            "expireAt": "2023-03-08T15:17:04.506Z"
        }
    ]
}

And

@Data
@Builder
public class MyResponse {
    private String personId;
    private String userId;
    private List<Details> details;
}
@Data
@Builder
public class Details {
    private String homeId;
    private Instant expireAt;
}

I am trying to deserialize the JSON String to MyResponse as :

Gson().fromJson(string, MyResponse.class)

but getting the below expcetion for expireAt field:

Expected BEGIN_OBJECT but was STRING at line 1 column 24 path $.details[0].expireAt

How can I resolve this ?

newLearner
  • 637
  • 1
  • 12
  • 20
  • Looking at [this Q&A](https://stackoverflow.com/q/22310143/6395627), it appears you need to register a "type adapter". This [other Q&A](https://stackoverflow.com/q/23072733/6395627) links to [a library](https://github.com/gkopff/gson-javatime-serialisers) that may already provide what you need. – Slaw Mar 09 '23 at 21:14
  • [gson decode instant](https://www.google.com/search?q=gson+decode+instant&rlz=1C5GCEM_enAU1020AU1020&oq=gson+decode+instant&aqs=chrome..69i57.4523j0j7&sourceid=chrome&ie=UTF-8) – MadProgrammer Mar 09 '23 at 21:25

1 Answers1

2

The exception you're getting is because the "expireAt" field in the JSON is a string, but in the Details class it's declared as an Instant type. You need to tell Gson how to convert the string to an Instant.

You can create a custom Gson deserializer for the Instant type, like this:

public class InstantDeserializer implements JsonDeserializer<Instant> {
  @Override
  public Instant deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    return Instant.parse(json.getAsString());
  }
}

Then, you can register this deserializer with Gson before parsing the JSON string:

Gson gson = new GsonBuilder()
            .registerTypeAdapter(Instant.class, new InstantDeserializer())
            .create();
MyResponse response = gson.fromJson(string, MyResponse.class);
Laurent
  • 523
  • 6
  • 15