Reputation: 15
I'm fairly new to java and Gson and I've been trying to parse some date from the nobelprize.org api. I've been able to parse through some of the info but when I include dates I seem to always hit errors. How would i go about fixing this error?
I've tried .setDateFormat("yyyy-MM-dd") but I still get the same error.
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
}
This is the error I get:
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"
*Edit: Example Json
"laureates": [
{
"id": "1",
"firstname": "Wilhelm Conrad",
"surname": "Röntgen",
"born": "1845-03-27",
"died": "1923-02-10",
"bornCountry": "Prussia (now Germany)",
"bornCountryCode": "DE",
"bornCity": "Lennep (now Remscheid)",
"diedCountry": "Germany",
"diedCountryCode": "DE",
"diedCity": "Munich",
"gender": "male",
"prizes": [
{
"year": "1901",
"category": "physics",
"share": "1",
"motivation": "\"in recognition of the extraordinary services he has rendered by the discovery of the remarkable rays subsequently named after him\"",
"affiliations": [
{
"name": "Munich University",
"city": "Munich",
"country": "Germany"
}
]
}
]
},
]
Upvotes: 0
Views: 1337
Reputation: 889
You can try to use JsonDeserializer
for Date
attributes.
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;
}
}
in your model class add JsonAdapter
for attributes
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
}
Upvotes: 1