GSON not parsing nested JSON objects properly - java

I have some data in the form of JSON, and was using the GSON library to parse it into a Java object to be used in later portions of the code. The JSON has nested objects, which don't seem to be getting parsed properly, and I can't figure out why, as the outer object is being converted as desired. Here is an example of the JSON data I'm looking at:
{
"title":"Emergency Services Headquarters",
"description":"",
"cid":"C70856",
"building_id":"4714",
"building_number":"3542",
"campus_code":"20",
"campus_name":"Busch",
"location":{
"name":"Emergency Services Headquarters",
"street":"129 DAVIDSON ROAD",
"additional":"",
"city":"Piscataway",
"state":"New Jersey",
"state_abbr":"NJ",
"postal_code":"08854-8064",
"country":"United States",
"country_abbr":"US",
"latitude":"40.526306",
"longitude":"-74.461470"
},
"offices":[
"Emergency Services"
]
}
I used codebeautify to create the Java object classes required for the JSON (everything is within Building.java):
public class Building {
private String title;
private String description;
private String cid;
private String building_id;
private String building_number;
private String campus_code;
private String campus_name;
Location LocationObject;
ArrayList < Object > offices = new ArrayList < Object > ();
//Setters and getters have been omitted
}
class Location {
private String name;
private String street;
private String additional;
private String city;
private String state;
private String state_abbr;
private String postal_code;
private String country;
private String country_abbr;
private String latitude;
private String longitude;
//Setters and getters have been omitted
}
Here is the code I'm using to parse the JSON, where the variable json is an input parameter for the method:
Gson obj = new Gson();
JsonArray buildingsArray = new JsonArray();
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(json);
buildingsArray = jsonElement.getAsJsonArray();
for (int i = 0; i < buildingsArray.size(); i++)
Building building = obj.fromJson(buildingsArray.get(i), Building.class);
When I call methods such as building.getTitle() or building.getCid(), I get the appropriate values, however when I do building.getLocation() (where Location is a separate object), the code returns null. I have not been able to figure it out, is it an issue with the way GSON works? Or am I doing something wrong in my code?

First of all, change:
Location LocationObject;
to:
private Location location;
And, you can deserialise JSON much easier:
Gson gson = new GsonBuilder().create();
Building building = gson.fromJson(json, Building.class);

Json property name should match your POJO class properties, it should be location not LocationObject
public class Building {
private String title;
private String description;
private String cid;
private String building_id;
private String building_number;
private String campus_code;
private String campus_name;
Location location;
ArrayList < Object > offices = new ArrayList < Object > ();
//Setters and getters have been omitted
}

It seems that you have a bad naming. Your location object in Building class is called LocationObject when your object inside JSON is called location.

Related

How to convert an Array List of objects to Json [duplicate]

This question already has answers here:
How to wrap a List as top level element in JSON generated by Jackson
(2 answers)
How to convert List to Json in Java
(8 answers)
Closed 4 years ago.
I have an ArrayList which I want to transform into a JSON array of objects. How can I transform it?
Array is of type Kunde:
public class Kunde {
private String knr;
private String name1;
private String name2;
private String anrede;
private String strasse;
private String plz;
private String ort;
private String erfdat;
private String telefon;
private String fax;
private String handy;
private String lastbes;
private String email;
private String land;
for each member variable there is a getter and a setter.
I store it like this:
List<Kunde> Kunden = new ArrayList<Kunde>();
My JSON should look like this:
{
"kunden": [
{"name1": "hans", "name2": "peter"},
{...}
]
}
Play comes with play-json module which can do it. You might have to create a wrapping class to output the kunden root node:
public class Kunden {
private List<Kunde> kunden;
// getter and setter
}
Kunden root = new Kunden();
kunden.setKunden(...);
JsonNode rootNode = Json.toJson(root);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);
Note that ObjectMapper is used to pretty print.
See the official Play Framework 2.6.X docs: Mapping Java objects to JSON.
Try to do something like this
ArrayList<Kundle> list = new ArrayList<Kundle>();
list.add("yo");
list.add("yo");
JSONArray jsArray = new JSONArray(list);

Specified object from JSONObject

I have JSONObject which contains as shown below and created class Markets contained all fields. I want put JSONObject elements to created object of Markets.
Example: Markets markets = new Markets(),then put elements from JSONObject to markets and I want to be able to get markets.getInstrumentName(). How can I do this ?
I try using Gson, like this Markets markets = gson2.fromJson(jsonObject, Markets.class); but there are different types and it is wrong way.
JSONObject:
{
"map": {
"netChange": -81.0,
"instrumentType": "INDICES",
"percentageChange": -1.31,
"scalingFactor": 1,
"epic": "IX.D.FTSE.DAILY.IP",
"updateTime": "00:02:48",
"updateTimeUTC": "23:02:48",
"offer": 6095.8,
"instrumentName": "FTSE 100",
"high": 6188.3,
"low": 6080.8,
"streamingPricesAvailable": true,
"marketStatus": "TRADEABLE",
"delayTime": 0,
"expiry": "DFB",
"bid": 6094.8
}
}
Markets:
class Markets {
private double bid;
private double offer;
private int delayTime;
private String epic;
private String expiry;
private double high;
private double low;
private String instrumentName;
private String instrumentType;
private String marketStatus;
private double netChange;
private double percentageChange;
private int scalingFactor;
private boolean streamingPricesAvailable;
private String updateTime;
private String updateTimeUTC;
//getters and setters
}
Using Jackson library
JSONObject jsonObject = //...
ObjectMapper mapper = new ObjectMapper();
Markets markets = mapper.readValue(jsonObject.toString(), Markets.class);
Here is sample Code when you want to convert JSON to object :
yourObject = new Gson().fromJson(yourJSONObject.toString(), YourObject.class);
I'm using Gson 2.4. and it works fine.
compile 'com.google.code.gson:gson:2.4'

How to efficiently Parse Json to Object when different variables returned in each json string

I need some advice on JSON parsing in Java. For some real-time update, i get JSON response like following (server returned only the variables that has new values):
{"33":"7153", "170":"AA","151":10}
{"33":"7153","rate":0.5488,"45":"U05"}
{"33":"7153", "98":7.38,"132":583}
Any idea how do I efficiently write a parser to parse them to object instead of doing this every time?
String str = "{\"33\":\"7153\", \"170\":\"AA\",\"151\":10}";
JSONObject json = new JSONObject(str);
Product s = new Product();
if (json.has("33")) s.setCode(json.getString("33"));
if (json.has("170")) s.setName(json.getString("170"));
if (json.has("151")) s.setPointer(json.getString("151"));
if (json.has("98")) s.setPrice(json.getString("98"));
if (json.has("rate")) s.setRate(json.getString("rate"));
if (json.has("132")) s.setValue(json.getString("132"));
if (json.has("45")) s.setDescription(json.getString("45"));
Use Google Gson.
public class Product {
#SerializedName("33") private String code;
#SerializedName("170") private String name;
#SerializedName("151") private String pointer;
#SerializedName("98") private String price;
#SerializedName("rate") private String rate;
#SerializedName("132") private String value;
#SerializedName("45") private String description;
// setters, getters
}
And
String str = "{\"33\":\"7153\", \"170\":\"AA\",\"151\":10}";
Gson gson = new Gson();
Product s = gson.fromJson(str, Product.class);
in each setCode(string x), setName(string x), setPointer(string x), setPrice(string x)... give a check:
if(x == null)
return;
then when parsing Json you don't have to check Json's response have which key or not.

Gson to POJO, how to read the inner JSON Objects as part of the same POJO?

I have a JSON like below and would like to convert it using Gson to one POJO.
I am trying to figure out how to basically cut down the inner nested objects like desc to be treated as part of the same Java object, instead of creating a new POJO named Desc.
Is there a way to do this with Serialized Names to look into nested JSON objects?
Thanks in advance!
JSON to be converted to POJO
{
'name': name,
'desc': {
'country': country,
'city': city,
'postal': postal,
'street': street,
'substreet': substreet,
'year': year,
'sqm': sqm
},
'owner': [owner],
'manager': [manager],
'lease': {
'leasee': [
{
'userId': leaseeId,
'start': leaseeStart,
'end': leaseeeEnd
}
],
'expire': leaseExpire,
'percentIncrease': leasePercentIncrease,
'dueDate': dueDate
},
'deposit': {
'bank': 'Sample Bank',
'description': 'This is a bank'
}
}
Custom POJO
public class Asset {
private String mId;
#SerializedName("name")
private String mName;
private String mCountry;
private String mCity;
private String mPostal;
private String mStreet;
private String mSubstreet;
private int mYear;
private int mSqm;
#SerializedName("owner")
private List<String> mOwners;
#SerializedName("manager")
private List<String> mManagers;
private List<Leasee> mLeasees;
private DateTime mLeaseExpiration;
private int mPercentIncrease;
private int mDueDate;
private String mDepositBank;
private String mDepositDescription;
}

Convert multi type of lists into json using gson

How can I use gson to convert my object into json.I have two array lists in my object.I know the convertion if there is a single array list in the object by giving the type at gson.toJson(Object.class,).
Here my problem is I have two array lists which are related to two different objects.
Here is my object:
public class Profile
{
private String doctor_id;
private String name;
private String location;
private String phone;
private String minimum_amount;
private String minimum_slot;
private List<specialties> specialties;
private List<education> education;
}
public class specialties {
private String specialty_id;
private String specialization;
private List<super_specialties> super_specialties;
}
public class super_specialties {
private String super_specialty_id;
private String super_specialization;
}
public class education {
private String qualification;
private String yearOfCompletion;
}
Please guid me how to use gson to convert this object into json.
Thanks,
Chaitanya.K
Have you tried this.
Hope it help. Worked for me.
Gson gson = new Gson();
String obj = gson.toJson(ProfileClassObject);
System.out.println(obj);
This obj variable has the Json which you want.

Categories

Resources