简体   繁体   中英

Failed to parse “Date” from JSON

I have the following JSON string in REST response:

"09:41:50 CET"

For the corresponding POJO mapper class has a Date type for this field. So I've tried Jackson and GSON to map JSON to Java Object, but both failed with the following messages:

GSON: java.text.ParseException: Failed to parse date ["09:41:50 CET"]: Invalid number: 09:4

Jackson: InvalidFormatException: Cannot deserialize value of type `java.util.Date` from
                                 String "09:41:50 CET": not a valid representation

Sadly I cannot modify in the POJO class the type to string or anything else, because I get those POJO classes from mvn dependency.

Try with this:

public static void main(String[] args) throws ParseException {

    String jsonStr = "{ \"date\" : \"09:41:50 CET\" }";
    Gson gson = new GsonBuilder().setDateFormat("HH:mm:ss").create();
    JsonElement element = gson.fromJson (jsonStr, JsonElement.class);

    OnlyDate date =gson.fromJson(element, new TypeToken<OnlyDate>(){}.getType());

    System.out.println(date.getDate());

}

My example DTO is:

public class OnlyDate implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @SerializedName("date")
    private Date date ;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }


}

You have to specify the dateFormat of your gson Element

不确定要使用哪种类型的支架,但是如果您使用的是弹簧支架,则可以通过实现自定义Converter来实现,请查看https://www.baeldung.com/spring-mvc-custom-data-binder上的示例。

Since Jackson v2.0, you can use @JsonFormat annotation directly on Object members;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm:ss", timezone="CET")
private Date date;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM