{
"Response": {
"MetaInfo": {
"Timestamp": "2011-11-21T14:55:06.556Z"
},
"View": [
{
"_type": "SearchResultsViewType",
"ViewId": 0,
"Result": [
{
"Relevance": 0.56,
"MatchQuality": {
"Country": 1,
"State": 1,
"County": 1,
"City": 1,
"PostalCode": 1
},
"Location": {
"LocationType": "point",
"DisplayPosition": {
"Latitude": 50.1105,
"Longitude": 8.684
},
"MapView": {
"_type": "GeoBoundingBoxType",
"TopLeft": {
"Latitude": 50.1194932,
"Longitude": 8.6699768
},
"BottomRight": {
"Latitude": 50.1015068,
"Longitude": 8.6980232
}
},
"Address": {
"Country": "DEU",
"State": "Hessen",
"County": "Frankfurt am Main",
"City": "Frankfurt am Main",
"District": "Frankfurt am Main",
"PostalCode": "60311",
"AdditionalData": [
{
"value": "Germany",
"key": "CountryName"
}
]
}
}
}
]
}
]
}
}
I am trying to retrieve the postal code from the above JSON. I am using gson to parse it. I am very new to JSON and from what i read from all the posts here(some very similar to this), I understood that the fields name should be as it is. So I understand i have to make 4 classes viz Response, view, Result and Address. I made them static nested classes, but I am only getting null value as output. In the next JSON, I have multiple addresses. But I am stuck on this single response.
For a short example, I try to retrieve Timestamp with this code, but it gives me a null value
public class ParseJSON {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("try.json"));
Gson gson = new GsonBuilder().create();
Pojo pojo = gson.fromJson(br,Pojo.class);
System.out.println(Pojo.Response.MetaInfo.Timestamp);
br.close();
}
}
class Pojo {
public Pojo() { }
static class Response{
static class MetaInfo {
static public String Timestamp;
public String getTimestamp() {
return Timestamp;
}
}
}
}
To make your Timestamp example work, try:
public class ParseJSON {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("try.json"));
Gson gson = new GsonBuilder().create();
Pojo pojo = gson.fromJson(br, Pojo.class);
System.out.println(pojo.Response.MetaInfo.Timestamp);
br.close();
}
}
class Pojo {
Response Response = new Response();
}
class Response {
MetaInfo MetaInfo = new MetaInfo();
}
class MetaInfo {
String Timestamp;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With