How to deserialize String to java Instant

I have a a JSON string as :

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


public class MyResponse {
    private String personId;
    private String userId;
    private List<Details> details;
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 ?

>Solution :

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> {
  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())
MyResponse response = gson.fromJson(string, MyResponse.class);

Leave a Reply