Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"
        }
    ]
}

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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> {
  @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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading