I think this example is going to help you
You need to map a class for the entire response. So you need to have class with the next fields:
class Response {
String cod
int message
City city
...
}
Pergunta
After struggling with errors in my java code and resolving them I finally have proceeded to the running stage, but I get an exception error after I run it. I am trying to convert json from a weather API to java object using jackson library. I have several classes for setting and getting the java objects including: City.java, Coord.java, List1.java, Temp.java, Weather.java. I have class named as usertest.java for mapping the objects as a test.
My code is as below:
A sample of my getters and setters: City.java
package weather.data;
//import java.util.List;
public class City{
private Coord coord;
private String country;
private Number id;
private String name;
private Number population;
...
//getters and setters
}
usertest.java
package weather.data;
import weather.data.City;
import weather.data.Coord;
import weather.data.list1;
import weather.data.Temp;
import weather.data.Weather;
import com.fasterxml.jackson.core.JsonParseException;
//import com.fasterxml.jackson.annotation.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonMappingException;
import java.io.File;
import java.net.URL;
import java.io.IOException;
public class usertest {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException
{
URL jsonUri = new URL("https://gist.githubusercontent.com/anonymous/4b32c7ef1ceb5dd48bf5/raw/ef1987551faa3fb61473bb0e7aad70a228dc36d6/gistfile1.txt");
ObjectMapper mapper = new ObjectMapper();
City city = mapper.readValue(jsonUri, City.class);
System.out.println(city.getCoord());
}
}
And the error I get after running the code: Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "cod" (class weather.data.City), not marked as ignorable (5 known properties: , "coord", "country", "id", "name", "population"])
Any help would highly appreciated.
Solução
I think this example is going to help you
You need to map a class for the entire response. So you need to have class with the next fields:
class Response {
String cod
int message
City city
...
}
Outras dicas
Your json
representation is not matching with City.java
:
json:
{
"cod": "200",
"message": 0.0035,
"city": {
"id": 1851632,
"name": "Shuzenji",
"coord": {
"lon": 138.933334,
"lat": 34.966671
},
"country": "JP",
"population": 0
},
"cnt": 10,
"list": [..]
}
City
class though is fine but you need to create another class having cod
, message
, city
, cnt
and list
attribute where city
attribute should be of type City
.
Other (unclean) alternate could be to add these property and set them @Ignore
..