I have some json, with a sequence of entries which look like this (I’ve simplified it tofocus on relevant issue which is why it looks a little redundant):
{“name”:”ISPC Seychelles”,”company”:{“name”:”ISPC
Seychelles”,”id”:3427640}}
sometimes however the company property is set to null:
{“name”:”Westin Miyako Kyoto”, “company”:null}
I have defined my classes like this (sorry for the public access modifiers, will change these when I get this bit of code working :)) :
class Entry {
public String name=;
public Company company;
public String toString() {
return name + ";" + company;
}
}
class Company {
public String name;
public int id;
public String toString() {
return "Company: " + name;
}
}
In my code, I try to use gson to deserialise the JSON contained in the variable called output:
while ((output = br.readLine()) != null) {
Gson gson = new Gson();
Reply reply = gson.fromJson(output, Reply.class);
Entry[] entries = reply.entries;
for (int i=0; i < entries.length; i++) {
System.out.print(entries[i]+ "\n") ;
}
}
This works fine when the company element is populated as in the first example in the JSON:
ISPC Seychelles;Company: ISPC Seychelles
However, if the element is not populated as in the second example, I get the following output:
Westin Miyako Kyoto; null
What I would like is the following output:
Westin Miyako Kyoto; Company: null
The
toString()representation ofCompanyis controlled by theCompanyobject, so there is no way you can get the representation you want if theCompanyobject is null. The only way to do it is to have something like the following in yourEntryclass’toString():