Java 8 LocalDateTime deserialized using Gson

前端 未结 4 866
無奈伤痛
無奈伤痛 2020-12-01 14:04

I have JSONs with a date-time attribute in the format \"2014-03-10T18:46:40.000Z\", which I want to deserialize into a java.time.LocalDateTime field using Gson.

When

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 14:20

    Following worked for me.

    Java:

    Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer() { 
    @Override 
    public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
    
    return LocalDateTime.parse(json.getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); } 
    
    }).create();
    
    Test test = gson.fromJson(stringJson, Test.class);
    

    where stringJson is a Json which is stored as String type

    Json:

    "dateField":"2020-01-30 15:00"

    where dateField is of LocalDateTime type which is present in the stringJson String variable.

提交回复
热议问题