com.google.gson.JsonSyntaxException when trying to parse Date/Time in json

前端 未结 3 1479
有刺的猬
有刺的猬 2021-01-11 09:17

I\'m using RestTemplete to get json data from a rest api and I\'m using Gson to parse data from json format to Object

Gson gson = new Gson();

restTemplate =         


        
3条回答
  •  自闭症患者
    2021-01-11 10:06

    The 1382828400000 value is a long (time in milliseconds). You are telling GSON that the field is a Date, and it cannot automatically convert a long into a Date.

    You have to specify your fields as long values

    private long dateParution;
    private long heureParution;
    private long dateLimite;
    private long heureLimite;
    

    and after GSON casts the JSON string to the desired Appel class instance, construct another object with those fields as Dates and convert them while assigning the values to the new object.

    Another alternative is to implement your own Custom Deserializer:

     public class CustomDateDeserializer extends DateDeserializer {
         @Override
         public Date deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
             // get the value from the JSON
             long timeInMilliseconds = Long.parseLong(jsonParser.getText());
    
             Calendar calendar = Calendar.getInstance();
             calendar.setTimeInMillis(timeInMilliseconds);
             return calendar.getTime();
         }
     }
    

    You have to set this custom deserializer on your desired fields, on the setter methods, like:

    @JsonDeserialize(using=CustomDateDeserializer.class)
    public void setDateParution(Date dateParution) {
        this.dateParution = dateParution;
    }
    

提交回复
热议问题