JSON parsing issue when the response does not contain values - java

I want to parse a JSON using Java and I managed to do this for the case when I get a response with values from the GET call. My problem comes when the response comes with no values because I get the exception: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of com.footbal.dtoStatistics.Statistics out of START_ARRAY token
at
[Source: (String)"{"api":{"results":0,"statistics":[]}}"; line: 1, column: 34] (through reference chain: com.footbal.dtoStatistics.StatisticsResponse["api"]->com.footbal.dtoStatistics.Api["statistics"])
My JSON without values looks like this:
{
"api": {
"results": 0,
"statistics": []
}
}
My Json with values for which the parsing works looks like this:
{
"api": {
"results": 16,
"statistics": {
"Shots on Goal": {
"home": "3",
"away": "9"
},
"Shots off Goal": {
"home": "5",
"away": "3"
},
"Total Shots": {
"home": "11",
"away": "16"
},
"Blocked Shots": {
"home": "3",
"away": "4"
},
"Shots insidebox": {
"home": "4",
"away": "14"
},
"Shots outsidebox": {
"home": "7",
"away": "2"
},
"Fouls": {
"home": "10",
"away": "13"
},
"Corner Kicks": {
"home": "7",
"away": "4"
},
"Offsides": {
"home": "2",
"away": "1"
},
"Ball Possession": {
"home": "55%",
"away": "45%"
},
"Yellow Cards": {
"home": "0",
"away": "2"
},
"Red Cards": {
"home": null,
"away": null
},
"Goalkeeper Saves": {
"home": "7",
"away": "1"
},
"Total passes": {
"home": "543",
"away": "436"
},
"Passes accurate": {
"home": "449",
"away": "355"
},
"Passes %": {
"home": "83%",
"away": "81%"
}
}
}
}
And the classes I used for the parsing are:
public class StatisticsResponse {
Api api;
public Api getApi() {
return api;
}
public void setApi(Api api) {
this.api = api;
}
}
public class Api {
int results;
Statistics statistics;
public int getResults() {
return results;
}
public void setResults(int results) {
this.results = results;
}
public Statistics getStatistics() {
return statistics;
}
public void setStatistics(Statistics statistics) {
this.statistics = statistics;
}
}
#JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE)
public class Statistics {
#JsonProperty ("Shots on Goal")
Stats ShotsonGoal;
#JsonProperty ("Shots off Goal")
Stats ShotsoffGoal;
#JsonProperty ("Total Shots")
Stats TotalShots;
#JsonProperty ("Blocked Shots")
Stats BlockedShots;
#JsonProperty ("Shots insidebox")
Stats Shotsinsidebox;
#JsonProperty ("Shots outsidebox")
Stats Shotsoutsidebox;
Stats Fouls;
#JsonProperty ("Corner Kicks")
Stats CornerKicks;
Stats Offsides;
#JsonProperty ("Ball Possession")
StatsPercent BallPossesion;
#JsonProperty ("Yellow Cards")
Stats YellowCards;
#JsonProperty ("Red Cards")
Stats RedCards;
#JsonProperty ("Goalkeeper Saves")
Stats GoalkeeperSaves;
#JsonProperty ("Total passes")
Stats Totalpasses;
#JsonProperty ("Passes accurate")
Stats Passesaccurate;
#JsonProperty("Passes %")
StatsPercent Passes;
public Stats getShotsonGoal() {
return ShotsonGoal;
}
public void setShotsonGoal(Stats shotsonGoal) {
ShotsonGoal = shotsonGoal;
}
public Stats getShotsoffGoal() {
return ShotsoffGoal;
}
public void setShotsoffGoal(Stats shotsoffGoal) {
ShotsoffGoal = shotsoffGoal;
}
public Stats getTotalShots() {
return TotalShots;
}
public void setTotalShots(Stats totalShots) {
TotalShots = totalShots;
}
public Stats getBlockedShots() {
return BlockedShots;
}
public void setBlockedShots(Stats blockedShots) {
BlockedShots = blockedShots;
}
public Stats getShotsinsidebox() {
return Shotsinsidebox;
}
public void setShotsinsidebox(Stats shotsinsidebox) {
Shotsinsidebox = shotsinsidebox;
}
public Stats getShotsoutsidebox() {
return Shotsoutsidebox;
}
public void setShotsoutsidebox(Stats shotsoutsidebox) {
Shotsoutsidebox = shotsoutsidebox;
}
public Stats getFouls() {
return Fouls;
}
public void setFouls(Stats fouls) {
Fouls = fouls;
}
public Stats getCornerKicks() {
return CornerKicks;
}
public void setCornerKicks(Stats cornerKicks) {
CornerKicks = cornerKicks;
}
public Stats getOffsides() {
return Offsides;
}
public void setOffsides(Stats offsides) {
Offsides = offsides;
}
public StatsPercent getBallPossesion() {
return BallPossesion;
}
public void setBallPossesion(StatsPercent ballPossesion) {
BallPossesion = ballPossesion;
}
public Stats getYellowCards() {
return YellowCards;
}
public void setYellowCards(Stats yellowCards) {
YellowCards = yellowCards;
}
public Stats getRedCards() {
return RedCards;
}
public void setRedCards(Stats redCards) {
RedCards = redCards;
}
public Stats getGoalkeeperSaves() {
return GoalkeeperSaves;
}
public void setGoalkeeperSaves(Stats goalkeeperSaves) {
GoalkeeperSaves = goalkeeperSaves;
}
public Stats getTotalpasses() {
return Totalpasses;
}
public void setTotalpasses(Stats totalpasses) {
Totalpasses = totalpasses;
}
public Stats getPassesaccurate() {
return Passesaccurate;
}
public void setPassesaccurate(Stats passesaccurate) {
Passesaccurate = passesaccurate;
}
public StatsPercent getPasses() {
return Passes;
}
public void setPasses(StatsPercent passes) {
Passes = passes;
}
}
try {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
StatisticsResponse apiResponse = mapper.readValue(statisticsResponse, StatisticsResponse.class);
statisticsList = apiResponse.getApi().getStatistics();
Why would it work for the case with values and for the case when I get no values it fails? I cannot see what I did wrong.
Can anyone help me with this parsing?

In your case, Json with values and without values are different. Without values, your JSON is having Statistics as a List. While the other case, it is not a List. Your classes satisfy the second case where there are values. When there are no values, class Api should contain List<Statistics> instead of Statistics.
Ideally, try to follow same structure for both cases. If Statistics never will be list, then change:
{
"api": {
"results": 0,
"statistics": []
}
}
to
{
"api": {
"results": 0,
"statistics": {}
}
}
Else if Statistics will return List, change
{
"api": {
"results": 16,
"statistics": {
"Shots on Goal": {
"home": "3",
"away": "9"
},
"Shots off Goal": {
"home": "5",
"away": "3"
},...
}}}
to
{
"api": {
"results": 16,
"statistics": [{
"Shots on Goal": {
"home": "3",
"away": "9"
},
"Shots off Goal": {
"home": "5",
"away": "3"
},...
}]
}}

A solution to this issue is quite simple: change type of statistics to Object and update getter/setter and untyped mapping will work fine.
class Api {
int results;
Object statistics;
public int getResults() {
return results;
}
public void setResults(int results) {
this.results = results;
}
public Object getStatistics() {
return statistics;
}
public void setStatistics(Object statistics) {
this.statistics = statistics;
}
}
Test code produces expected output:
String emptyStats = "{\n" +
" \"api\": {\n" +
" \"results\": 0,\n" +
" \"statistics\": []\n" +
" }\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//StatisticsResponse apiResponse = mapper.readValue(json, StatisticsResponse.class);
StatisticsResponse apiResponse = mapper.readValue(emptyStats, StatisticsResponse.class);
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(apiResponse);
System.out.println(json);
// ----------------
{
"api" : {
"results" : 0,
"statistics" : [ ]
}
}

Related

I want to add a new Object inside a Json Object in JAVA with JSONObject

Im trying to make a JAVA application that makes a json file with the data that i send, but when i send new data, the last data the data is just replaced
the first method called
az.addUser("John", "10", "star");
the JSON
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
}
second method called
az.addUser("Kevin", "20", "energy");
The JSON Expected
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "energy"
}
}
the REAL JSON
{
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "Energy"
}
}
The Method
public void addUser(String name, String score, String type){
FileWriter wf = new FileWriter("exit.json");
JSONObject json;
JSONObject jsonInternal = new JSONObject();
jsonInternal.put("name", name);
jsonInternal.put("score", score);
jsonInternal.put("type", type);
json = new JSONObject();
json.put("user", jsonInternal);
wf.write(json.toJSONString());
wf.close();
}
You need to write a JSON array, not a JSON object. The code below is strictly pseudocode, as I do not know which library JSONObject comes from.
import java.io.FileWriter;
import java.io.IOException;
public class UserListWriter {
private String filename;
private JSONArray usersJson;
public UserListWriter(String filename) {
this.filename = filename;
this.usersJson = new JSONArray();
}
public UserListWriter addUser(String name, int score, String type) {
JSONObject userJson = new JSONObject();
userJson.put("name", name);
userJson.put("score", score);
userJson.put("type", type);
usersJson.put(userJson);
return this;
}
public UserListWriter write() throws IOException {
FileWriter wf = new FileWriter(this.filename);
wf.write(usersJson.toJSONString());
wf.close();
return this;
}
public static void main(String[] args) {
try {
new UserListWriter("exit.json")
.addUser("John", 10, "star")
.addUser("Kevin", 20, "energy")
.write();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Theoretical output:
[{
"name": "John",
"score": 10,
"type": "star"
}, {
"name": "Kevin",
"score": 20,
"type": "energy"
}]

How to "break" a JSON tree in down into separate lists starting from the parent down to each child connected in Java?

I have the following JSON which the children could have more child objects:
{
"color": "red",
"list": [{
"color": "blue",
"list": [{
"color": "yellow"
}, {
"color": "black",
"list": [{
"color": "purple"
}, {
"color": "white"
}]
}]
},
{
"color": "green",
"list": [{
"color": "pink",
"list": [{
"color": "gray"
}, {
"color": "brown"
}]
}]
}
]
}
from the following tree:
COLOR TREE
I want to break down the diagram into separate lists from the parent down to each child connected:
LIST1 = red,blue
LIST2 = red,blue,yellow
LIST3 = red,blue,black
LIST4 = red,blue,black,purple
LIST5 = red,blue,black,white
LIST6 = red,green
LIST7 = red,green,pink
LIST8 = red,green,pink,grey
LIST9 = red,green,pink,brown
This was an interesting one, tried to solve this. Please, let me know, if the solution helps. I have implemented this in Java.
// Java program to print all the node to leaf path
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class Color {
private String color;
private List<Color> list;
public Color() {
//default
}
public Color(String color) {
this.color = color;
list = new ArrayList();
}
public Color(String color, List<Color> list) {
this.color = color;
this.list = list;
}
public void setColor(String color) {
this.color = color;
}
public void add(Color c) {
this.list.add(c);
}
public void setList(List<Color> list) {
this.list = list;
}
public String getColor() {
return color;
}
public List<Color> getList() {
return this.list;
}
}
class ColorTree {
Color root;
/*Given a binary tree, print out all of its root-to-leaf
paths, one per line. Uses a recursive helper to do
the work.*/
void printPaths(Color node) {
String[] path = new String[1000];
printPathsRecur(node, path, 0);
}
/* Recursive helper function -- given a node, and an array
containing the path from the root node up to but not
including this node, print out all the root-leaf paths.*/
void printPathsRecur(Color node, String[] path, int pathLen) {
if (node == null)
return;
/* append this node to the path array */
path[pathLen] = node.getColor();
pathLen++;
printArray(path, pathLen);
/* it's a leaf, so print the path that led to here */
if (node.getList() == null || node.getList().size() == 0) {
//printArray(path, pathLen);
} else {
Iterator<Color> colorIter = node.getList().iterator();
/* otherwise try subtrees */
while (colorIter.hasNext()) {
printPathsRecur(colorIter.next(), path, pathLen);
}
}
}
/* Utility function that prints out an array on a line. */
void printArray(String[] names, int len) {
int i;
for (i = 0; i < len; i++) {
System.out.print(names[i] + " ");
}
System.out.println();
}
private static Color convertJsonToColor(String input) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
return mapper.readValue(input, Color.class);
}
// driver program to test above functions
public static void main(String[] args) throws IOException {
String jsonInput = "{ \"color\": \"red\", \"list\": [{ \"color\": \"blue\", \"list\": [{ \"color\": \"yellow\" }, { \"color\": \"black\", \"list\": [{ \"color\": \"purple\" }, { \"color\": \"white\" }] }] }, { \"color\": \"green\", \"list\": [{ \"color\": \"pink\", \"list\": [{ \"color\": \"gray\" }, { \"color\": \"brown\" }] }] } ] }";
ColorTree tree = new ColorTree();
tree.root = convertJsonToColor(jsonInput);
/* Let us test the built tree by printing Insorder traversal */
tree.printPaths(tree.root);
}
}

Taking user input retrieving details from json file and print it in java

Data.json:
{"UniversalWord": {"UniversalWord": [
{
"uw_id": 1,
"HeadWord": {"word": "aare"},
"Restriction": {"SemanticRelations": {"feat": [
{
"att": "restriction_type",
"value": "iof"
},
{
"att": "target",
"val": " "
}
]}},
"NLDescription": {
"Gloss": {"feat": {
"att": "Description",
"val": "\"A RIVER IN NORTH CENTRAL SWITZERLAND THAT RUNS NORTHEAST INTO THE RHINE\""
}},
"Lemma": {"feat": {
"att": "word",
"val": "aare"
}},
"Example": {"feat": {
"att": "description",
"val": "\"\""
}}
},
"MetaInfo": {
"Frequency": {"freq": ""},
"UWSource": {"Source_id": "WORDNET"}
}
},
{
"uw_id": 2,
"HeadWord": {"word": "aarhus"},
"Restriction": {"SemanticRelations": {"feat": [
{
"att": "restriction_type",
"value": "iof"
},
{
"att": "target",
"val": " "
},
{
"att": "restriction_type",
"value": "equ"
},
{
"att": "target",
"val": " "
}
]}},
"NLDescription": {
"Gloss": {"feat": {
"att": "Description",
"val": "\"PORT CITY OF DENMARK IN EASTERN JUTLAND\""
}},
"Lemma": {"feat": {
"att": "word",
"val": "aarhus"
}},
"Example": {"feat": {
"att": "description",
"val": "\"\""
}}
},
"MetaInfo": {
"Frequency": {"freq": ""},
"UWSource": {"Source_id": "WORDNET"}
}
}
]}}
Required output:
Word Searched: aare
uwid = 1
headword = aare
semantic relation value = iof
target = ""
gloss = A RIVER IN NORTH CENTRAL SWITZERLAND THAT RUNS NORTHEAST INTO THE RHINE
lemma = aare
example = ""
frequency = ""
Source_ID = wordnet
code.java
public class SearchJson
{
public void SearchValueInJson(StringBuilder sb)
{
try
{
String jsonData = sb.toString();
JSONObject jobj = new JSONObject(jsonData);
Map<String,String> map = new HashMap<String,String>();
iterateJson(jobj,map);
System.out.println(map.toString());
}
catch(Exception e)
{
System.out.println(e);
}
}
public void iterateJson(JSONObject jobj,Map map)
{
for(Object o : jobj.keySet())
{
if(jobj.get(o.toString())instanceof JSONObject)
iterateJson(jobj.getJSONObject(o.toString()),map);
else
map.put(o.toString(), jobj.get(o.toString()));
}
}
}
this code i tried but it is not giving me expected output.
How to retrieve this information from the json file? I'm not getting the proper solution for it. Please give code for this. And assume that you don't know key values of data on that basis have to retrieve.
Check the below code snippet, this may solve your problem.
JSONObject jobj = new JSONObject(jsonData);
JSONArray arr = jobj.getJSONObject("UniversalWord").getJSONArray("UniversalWord");
for (int i = 0; i < arr.length(); i++)
{
String uw_id = arr.getJSONObject(i).getString("uw_id");
System.out.println(uw_id);
String headWord = arr.getJSONObject(i).getJSONObject("HeadWord").getString("word");
System.out.println(headWord);
String nLDescription = arr.getJSONObject(i).getJSONObject("NLDescription").getJSONObject("Gloss").getJSONObject("feat").getString("val");
System.out.println(nLDescription);
}

Google Gson - com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT

Here is the object I try to deserialize:
public class DomaineBO {
private String nom;
private Set<String> codesQC;
private Set<String> codesSql;
...
Here are my JSon data:
[
{
"id":30,
"nom":"Usafe",
"gere":true,
"codesQC":[
{
"id":40,
"nom":"ServicesTransversaux",
"nomHTML":"ServicesTransversaux"
},
{
"id":41,
"nom":"%22Services%20Transversaux%22",
"nomHTML":"\"Services Transversaux\""
}
],
"codesSql":[
{
"id":61,
"nom":"USAF"
}
]
},
{
"id":33,
"nom":"Epublishing",
"gere":true,
"codesQC":[
{
"id":45,
"nom":"ServicesDocumentaires",
"nomHTML":"ServicesDocumentaires"
}
],
"codesSql":[
{
"id":64,
"nom":"EDIT"
}
]
},
{
"id":25,
"nom":"Commons",
"gere":true,
"codesQC":[
{
"id":34,
"nom":"Commons",
"nomHTML":"Commons"
}
],
"codesSql":[
{
"id":82,
"nom":"COM"
}
]
},
{
"id":22,
"nom":"Finance",
"gere":true,
"codesQC":[
{
"id":27,
"nom":"%22Refonte%20Contentieux%22",
"nomHTML":"\"Refonte Contentieux\""
},
{
"id":28,
"nom":"Finance",
"nomHTML":"Finance"
},
{
"id":29,
"nom":"%22Refonte%20Finance%20Client%22",
"nomHTML":"\"Refonte Finance Client\""
}
],
"codesSql":[
{
"id":45,
"nom":"FINA"
}
]
},
{
"id":32,
"nom":"Inconnu",
"gere":true,
"codesQC":[
],
"codesSql":[
]
},
{
"id":31,
"nom":"Marketing",
"gere":true,
"codesQC":[
{
"id":42,
"nom":"Marketing_ActionsCom",
"nomHTML":"Marketing_ActionsCom"
},
{
"id":44,
"nom":"Vente",
"nomHTML":"Vente"
},
{
"id":43,
"nom":"Marketing_Produits",
"nomHTML":"Marketing_Produits"
}
],
"codesSql":[
{
"id":63,
"nom":"MARK"
}
]
},
{
"id":26,
"nom":"Facturation",
"gere":true,
"codesQC":[
{
"id":35,
"nom":"Facturation",
"nomHTML":"Facturation"
}
],
"codesSql":[
{
"id":54,
"nom":"FACT"
}
]
},
{
"id":24,
"nom":"Sinistre",
"gere":true,
"codesQC":[
{
"id":32,
"nom":"Sinistre",
"nomHTML":"Sinistre"
},
{
"id":33,
"nom":"Entreprise",
"nomHTML":"Entreprise"
}
],
"codesSql":[
{
"id":47,
"nom":"SINI"
}
]
},
{
"id":23,
"nom":"Partenaire",
"gere":true,
"codesQC":[
{
"id":31,
"nom":"Partenaire",
"nomHTML":"Partenaire"
},
{
"id":30,
"nom":"Partenaires",
"nomHTML":"Partenaires"
}
],
"codesSql":[
{
"id":46,
"nom":"PART"
}
]
},
{
"id":1,
"nom":"Contrat",
"gere":true,
"codesQC":[
{
"id":24,
"nom":"Contrat",
"nomHTML":"Contrat"
}
],
"codesSql":[
{
"id":42,
"nom":"CONT"
}
]
},
{
"id":29,
"nom":"Services Transverses",
"gere":true,
"codesQC":[
{
"id":39,
"nom":"%22Services%20Transversaux%22",
"nomHTML":"\"Services Transversaux\""
},
{
"id":38,
"nom":"ServicesTransversaux",
"nomHTML":"ServicesTransversaux"
}
],
"codesSql":[
{
"id":58,
"nom":"SECU"
},
{
"id":57,
"nom":"DMS"
},
{
"id":60,
"nom":"INDE"
},
{
"id":59,
"nom":"JBPM"
}
]
},
{
"id":28,
"nom":"Flux de données",
"gere":true,
"codesQC":[
{
"id":37,
"nom":"%22Flux%20de%20donn%C3%A9es%22",
"nomHTML":"\"Flux de données\""
}
],
"codesSql":[
{
"id":81,
"nom":"FLUX"
}
]
},
{
"id":27,
"nom":"Reprise",
"gere":true,
"codesQC":[
{
"id":36,
"nom":"Reprise",
"nomHTML":"Reprise"
}
],
"codesSql":[
{
"id":55,
"nom":"FINA"
}
]
},
{
"id":21,
"nom":"Batch",
"gere":true,
"codesQC":[
{
"id":25,
"nom":"Batch",
"nomHTML":"Batch"
}
],
"codesSql":[
{
"id":44,
"nom":"BATCH"
}
]
}
]
And here is how I try to convert them:
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
DomaineBO[] infos = (DomaineBO[]) gson.fromJson(getJSonResponse(url), clazz);
Arrays.asList(infos);
When I am at the operation to convert it in my class DomaineBO, I get the JsonSyntaxException with the message Expected a string but was BEGIN_OBJECT at line 1 column 51 path $[0].codesQC[0]
I supect it is because of the attributes that are Sets of Strings.
I could try to make it with arrays but I wanted to know if there is a better way?
It is because in code you have set of String. Make class CodeQC with fields id, nom, nomHTML and change
Set<String> codesQC
to
Set<CodeQC> codesQC

Parse a nested JSON using gson

{
"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;
}
}
}
}
If you only need the "PostalCode", you could use JsonParser instead of having a bunch of classes:
JsonParser jsonParser = new JsonParser();
JsonObject address = jsonParser.parse(json)
.getAsJsonObject().get("Response")
.getAsJsonObject().getAsJsonArray("View").get(0)
.getAsJsonObject().getAsJsonArray("Result").get(0)
.getAsJsonObject().get("Location")
.getAsJsonObject().getAsJsonObject("Address");
String postalCode = address.get("PostalCode").getAsString();
or for all results:
JsonArray results = jsonParser.parse(json)
.getAsJsonObject().get("Response")
.getAsJsonObject().getAsJsonArray("View").get(0)
.getAsJsonObject().getAsJsonArray("Result");
for (JsonElement result : results) {
JsonObject address = result.getAsJsonObject().get("Location").getAsJsonObject().getAsJsonObject("Address");
String postalCode = address.get("PostalCode").getAsString();
System.out.println(postalCode);
}
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;
}

Categories