解析日期Gson:NumberFormatException

时间:2019-04-10 06:39:37

标签: java json gson

我对java和Gson还是很陌生,我一直在尝试从nobelprize.org api解析某些日期。我已经能够解析一些信息,但是当我包含日期时,我似乎总是遇到错误。我该如何解决该错误?

我尝试了.setDateFormat(“ yyyy-MM-dd”),但仍然遇到相同的错误。

const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    const msg = {
      to: 'test@example.com',
      from: 'test@example.com',
      subject: 'Sending with SendGrid is Fun',
      text: 'and easy to do anywhere, even with Node.js',
      html: '<strong>and easy to do anywhere, even with Node.js</strong>',
    };
    sgMail.send(msg);
Gson mainparser = new GsonBuilder()
.setDateFormat("yyyy-MM-dd")
.create();

mainparser.fromJson(line, ParsedJson.class);
public class ParsedJson {

    List<Laureates> laureates;

    public List<Laureates> getLaureates() {
        return laureates;
    }

    public void setLaureates(List<Laureates> laureates) {
        this.laureates = laureates;
    }


}

这是我得到的错误:

public class Laureates {
    int id;
    String firstname;
    String surname;
    Date born;
    Date died;
    String bornCountry;
    String bornCountryCode;
    String bornCity;
    String diedCountry;
    String diedCountryCode;
    String diedCity;
    String gender;
    List<Prizes> prizes;
...Getters/Setters

}

*编辑:示例Json

java.lang.reflect.InvocationTargetException

Caused by: com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: For input string: "1845-03-27"

Caused by: java.lang.NumberFormatException: For input string: "1845-03-27"

1 个答案:

答案 0 :(得分:0)

您可以尝试对JsonDeserializer属性使用Date

public class DateDeserializer implements JsonDeserializer<Date> {

   public DateDeserializer() {
   }

    @Override
    public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
        String dateStr = element.getAsString();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        try {
            return format.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

在模型类中为属性添加JsonAdapter

public class Laureates {
    int id;
    String firstname;
    String surname;
    @JsonAdapter(DateDeserializer.class)
    Date born;
    @JsonAdapter(DateDeserializer.class)
    Date died;
    String bornCountry;
    String bornCountryCode;
    String bornCity;
    String diedCountry;
    String diedCountryCode;
    String diedCity;
    String gender;
    List<Prizes> prizes;
...Getters/Setters

}