Parsing Json data. Nested Objects giving an error - java

So i have this data as below and i am trying to parse the data, i can see a lot about parsing JSONArrays online however, not so much on objects within objects. I have had a go and am getting an error. Here is the Json response I am only trying to return the marked fields:
{
"geomagnetic-field-model-result": {
"model": "wmm",
"model_revision": "2020",
"date": {
"value": "2020-07-14"
},
"coordinates": {
"latitude": {
"units": "deg (north)",
"value": 0.0
},
"longitude": {
"units": "deg (east)",
"value": 0.0
},
"altitude": {
"units": "km",
"value": 0.00
}
},
"field-value": {
"total-intensity": {
"units": "nT",
"value": 123 //Return this*****************
},
"declination": {
"units": "deg (east)",
"value": -123 //Return this*****************
},
"inclination": {
"units": "deg (down)",
"value": 123 //Return this*****************
},
"north-intensity": {
"units": "nT",
"value": 123
},
"east-intensity": {
"units": "nT",
"value": -123
},
"vertical-intensity": {
"units": "nT",
"value": 123
},
"horizontal-intensity": {
"units": "nT",
"value": 123
}
},
"secular-variation": {
"total-intensity": {
"units": "nT/y",
"value": 123
},
"declination": {
"units": "arcmin/y (east)",
"value": 123
},
"inclination": {
"units": "arcmin/y (down)",
"value": 123
},
"north-intensity": {
"units": "nT/y",
"value": 123
},
"east-intensity": {
"units": "nT/y",
"value": 123
},
"vertical-intensity": {
"units": "nT/y",
"value": 123
},
"horizontal-intensity": {
"units": "nT/y",
"value": 123
}
}
}
}
My attempt at parsing currently looks like this:
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response;
String totalIntensity = jsonObject.getJSONObject("field-value").getJSONObject("total-intensity").getString("value");
String declination = jsonObject.getJSONObject("field-value").getJSONObject("declination").getString("value");
String inclination = jsonObject.getJSONObject("field-value").getJSONObject("inclination").getString("value");
} catch (JSONException e) {
Log.d("geoData", "Error recorded");
e.printStackTrace();
}
}
Am i totally wrong? Hopefully this is very easy for someone to put me right.

I assume that the response you get in the method is the whole JSON object that you have posted here.
You have a few issues:
Your data is not String it is Double or Integer, so you should use getDouble for example.
You forgot about one additional node geomagnetic-field-model-result.
You don't need to assign internal JSONObject jsonObject you can just use response.
To get to the values you should:
public void onResponse(JSONObject response) {
try {
// JSONObject jsonObject = response; you don't need this
Double totalIntensity = response
.getJSONObject("geomagnetic-field-model-result")
.getJSONObject("field-value")
.getJSONObject("total-intensity")
.getDouble("value");
Double declination = response
.getJSONObject("geomagnetic-field-model-result")
.getJSONObject("field-value")
.getJSONObject("declination")
.getDouble("value");
Double inclination = response
.getJSONObject("geomagnetic-field-model-result")
.getJSONObject("field-value")
.getJSONObject("inclination")
.getDouble("value");
// use it somehow
} catch (JSONException e) {
Log.d("geoData", "Error recorded");
e.printStackTrace();
}
}

Create a Schema and use the return values, it's much easier to work with
Example schema for your returned response made from http://www.jsonschema2pojo.org/
-----------------------------------com.example.Altitude.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Altitude {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Double value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
}
-----------------------------------com.example.Coordinates.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Coordinates {
#SerializedName("latitude")
#Expose
private Latitude latitude;
#SerializedName("longitude")
#Expose
private Longitude longitude;
#SerializedName("altitude")
#Expose
private Altitude altitude;
public Latitude getLatitude() {
return latitude;
}
public void setLatitude(Latitude latitude) {
this.latitude = latitude;
}
public Longitude getLongitude() {
return longitude;
}
public void setLongitude(Longitude longitude) {
this.longitude = longitude;
}
public Altitude getAltitude() {
return altitude;
}
public void setAltitude(Altitude altitude) {
this.altitude = altitude;
}
}
-----------------------------------com.example.Date.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Date {
#SerializedName("value")
#Expose
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
-----------------------------------com.example.Declination.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Declination {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.Declination_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Declination_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.EastIntensity.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class EastIntensity {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.EastIntensity_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class EastIntensity_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("geomagnetic-field-model-result")
#Expose
private GeomagneticFieldModelResult geomagneticFieldModelResult;
public GeomagneticFieldModelResult getGeomagneticFieldModelResult() {
return geomagneticFieldModelResult;
}
public void setGeomagneticFieldModelResult(GeomagneticFieldModelResult geomagneticFieldModelResult) {
this.geomagneticFieldModelResult = geomagneticFieldModelResult;
}
}
-----------------------------------com.example.FieldValue.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FieldValue {
#SerializedName("total-intensity")
#Expose
private TotalIntensity totalIntensity;
#SerializedName("declination")
#Expose
private Declination declination;
#SerializedName("inclination")
#Expose
private Inclination inclination;
#SerializedName("north-intensity")
#Expose
private NorthIntensity northIntensity;
#SerializedName("east-intensity")
#Expose
private EastIntensity eastIntensity;
#SerializedName("vertical-intensity")
#Expose
private VerticalIntensity verticalIntensity;
#SerializedName("horizontal-intensity")
#Expose
private HorizontalIntensity horizontalIntensity;
public TotalIntensity getTotalIntensity() {
return totalIntensity;
}
public void setTotalIntensity(TotalIntensity totalIntensity) {
this.totalIntensity = totalIntensity;
}
public Declination getDeclination() {
return declination;
}
public void setDeclination(Declination declination) {
this.declination = declination;
}
public Inclination getInclination() {
return inclination;
}
public void setInclination(Inclination inclination) {
this.inclination = inclination;
}
public NorthIntensity getNorthIntensity() {
return northIntensity;
}
public void setNorthIntensity(NorthIntensity northIntensity) {
this.northIntensity = northIntensity;
}
public EastIntensity getEastIntensity() {
return eastIntensity;
}
public void setEastIntensity(EastIntensity eastIntensity) {
this.eastIntensity = eastIntensity;
}
public VerticalIntensity getVerticalIntensity() {
return verticalIntensity;
}
public void setVerticalIntensity(VerticalIntensity verticalIntensity) {
this.verticalIntensity = verticalIntensity;
}
public HorizontalIntensity getHorizontalIntensity() {
return horizontalIntensity;
}
public void setHorizontalIntensity(HorizontalIntensity horizontalIntensity) {
this.horizontalIntensity = horizontalIntensity;
}
}
-----------------------------------com.example.GeomagneticFieldModelResult.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class GeomagneticFieldModelResult {
#SerializedName("model")
#Expose
private String model;
#SerializedName("model_revision")
#Expose
private String modelRevision;
#SerializedName("date")
#Expose
private Date date;
#SerializedName("coordinates")
#Expose
private Coordinates coordinates;
#SerializedName("field-value")
#Expose
private FieldValue fieldValue;
#SerializedName("secular-variation")
#Expose
private SecularVariation secularVariation;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getModelRevision() {
return modelRevision;
}
public void setModelRevision(String modelRevision) {
this.modelRevision = modelRevision;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public FieldValue getFieldValue() {
return fieldValue;
}
public void setFieldValue(FieldValue fieldValue) {
this.fieldValue = fieldValue;
}
public SecularVariation getSecularVariation() {
return secularVariation;
}
public void setSecularVariation(SecularVariation secularVariation) {
this.secularVariation = secularVariation;
}
}
-----------------------------------com.example.HorizontalIntensity.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class HorizontalIntensity {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.HorizontalIntensity_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class HorizontalIntensity_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.Inclination.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Inclination {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.Inclination_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Inclination_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.Latitude.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Latitude {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Double value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
}
-----------------------------------com.example.Longitude.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Longitude {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Double value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
}
-----------------------------------com.example.NorthIntensity.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NorthIntensity {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.NorthIntensity_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NorthIntensity_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.SecularVariation.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class SecularVariation {
#SerializedName("total-intensity")
#Expose
private TotalIntensity_ totalIntensity;
#SerializedName("declination")
#Expose
private Declination_ declination;
#SerializedName("inclination")
#Expose
private Inclination_ inclination;
#SerializedName("north-intensity")
#Expose
private NorthIntensity_ northIntensity;
#SerializedName("east-intensity")
#Expose
private EastIntensity_ eastIntensity;
#SerializedName("vertical-intensity")
#Expose
private VerticalIntensity_ verticalIntensity;
#SerializedName("horizontal-intensity")
#Expose
private HorizontalIntensity_ horizontalIntensity;
public TotalIntensity_ getTotalIntensity() {
return totalIntensity;
}
public void setTotalIntensity(TotalIntensity_ totalIntensity) {
this.totalIntensity = totalIntensity;
}
public Declination_ getDeclination() {
return declination;
}
public void setDeclination(Declination_ declination) {
this.declination = declination;
}
public Inclination_ getInclination() {
return inclination;
}
public void setInclination(Inclination_ inclination) {
this.inclination = inclination;
}
public NorthIntensity_ getNorthIntensity() {
return northIntensity;
}
public void setNorthIntensity(NorthIntensity_ northIntensity) {
this.northIntensity = northIntensity;
}
public EastIntensity_ getEastIntensity() {
return eastIntensity;
}
public void setEastIntensity(EastIntensity_ eastIntensity) {
this.eastIntensity = eastIntensity;
}
public VerticalIntensity_ getVerticalIntensity() {
return verticalIntensity;
}
public void setVerticalIntensity(VerticalIntensity_ verticalIntensity) {
this.verticalIntensity = verticalIntensity;
}
public HorizontalIntensity_ getHorizontalIntensity() {
return horizontalIntensity;
}
public void setHorizontalIntensity(HorizontalIntensity_ horizontalIntensity) {
this.horizontalIntensity = horizontalIntensity;
}
}
-----------------------------------com.example.TotalIntensity.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class TotalIntensity {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.TotalIntensity_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class TotalIntensity_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.VerticalIntensity.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class VerticalIntensity {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.VerticalIntensity_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class VerticalIntensity_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
So now along as the schema doesn't change this will return the values in the correct format

You can use Jackson like this:
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(input);
System.out.println(jsonNode.get("geomagnetic-field-model-result").get("field-value").get("total-intensity").get("value"));

Related

JsonIllegalstateexception:- Expected BEGIN_ARRAY but was String at line 1 column 61 . $ customer.Data

There is JSON file and i want get through POJO so i Created POJO file as well but at customer data it show in some error like i mention in title i don't know what's happening i mean my whole team don't why it's happening.
I've try everything which i would try but nothing is helping me out
{
"Success": true,
"Message": "Device Not Found",
"Customer_Data": [{
"customerid": 12365,
"customername": "Mukesh SHARMA",
"gender": "M",
"personalcontact": 999999999,
"homecontact": 999999999,
"emailid": "mukeshr334#gmail.com",
"address": "RockStar",
"designation": "Chief Life Insurance Advisor",
"stateid": 22,
"statename": "Uttar Pradesh",
"cityid": 557,
"cityname": "Sant Ravidas Nagar",
"pincode": 221304,
"birthdate": "14-11-1983",
"marriagedate": "2018-01-01",
"category": "-- Select --",
"mdrttick": false,
"profilepicture": "http://mdddddddtaupdate.in/profile_pic/12365.jpg",
"branchname": "ModelTown",
"branchcode": "123",
"licbranchid": 20596,
"division": "Delhi DO-II",
"licdivisionentryid": 51,
"password": "123456",
"employeename": "Shahnawaz Khan",
"empcontact": 999999999,
"empmail": "shane_madddian#yahoo.com",
"dealername": "Sachinder",
"deacontact": 999999999,
"deamail": "ddd#gamil.com",
"club_member": "-- Select --",
"lifeinsurance": false,
"nonlife": false,
"healthinsurance": false,
"mutualfunds": false,
"other": false,
"efrom": "A",
"edate": "2019-05-09 13:03:17.63214",
"website": "",
"maxdate": "01-01-2000 00:00:00"
}],
"Customer_Device": "",
"Customer_Event": "",
"All_Event": [{
"event_id": 6,
"event_name": "Test Event - 1",
"start_date": "01/06/2019",
"end_date": "02/06/2019",
"address_1": "Mumbai",
"address_2": "Mumbai",
"location_link": "https://goo.gl/maps/vTia6DQxwmiA5kvz6",
"pincode": 400060,
"state_id": 10,
"city_id": 355,
"sechudel": "Test",
"itinerary": "Test",
"edate": "2019-05-09T17:00:05.95592",
"eventimg": "http://zaidicorp.in/login/ProcessImage/636935218388448729.png"
}],
"Status": 2,
"Currentdate": "5/18/2019"
}
This is my POJO
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
public class OtpCheck implements Serializable {
#SerializedName("Success")
#Expose
private Boolean success;
#SerializedName("Message")
#Expose
private String message;
#SerializedName("Customer_Data")
#Expose
private List<CustomerData> customerData = null;
#SerializedName("Customer_Device")
#Expose
private String customerDevice;
#SerializedName("Customer_Event")
#Expose
private String customerEvent;
#SerializedName("All_Event")
#Expose
private List<EventDetail> getEventDetails = null;
#SerializedName("Status")
#Expose
private Integer status;
#SerializedName("Currentdate")
#Expose
private String currentdate;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<CustomerData> getCustomerData() {
return customerData;
}
public void setCustomerData(List<CustomerData> customerData) {
this.customerData = customerData;
}
public String getCustomerDevice() {
return customerDevice;
}
public void setCustomerDevice(String customerDevice) {
this.customerDevice = customerDevice;
}
public String getCustomerEvent() {
return customerEvent;
}
public void setCustomerEvent(String customerEvent) {
this.customerEvent = customerEvent;
}
public List<EventDetail> getEventDetails() {
return getEventDetails;
}
public void setEventDetails(List<EventDetail> getEventDetails) {
this.getEventDetails = getEventDetails;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCurrentdate() {
return currentdate;
}
public void setCurrentdate(String currentdate) {
this.currentdate = currentdate;
}
public static class EventDetail implements Serializable {
#SerializedName("event_id")
#Expose
private Integer eventId;
#SerializedName("event_name")
#Expose
private String eventName;
#SerializedName("start_date")
#Expose
private String startDate;
#SerializedName("end_date")
#Expose
private String endDate;
#SerializedName("address_1")
#Expose
private String address1;
#SerializedName("address_2")
#Expose
private String address2;
#SerializedName("location_link")
#Expose
private String locationLink;
#SerializedName("pincode")
#Expose
private Integer pincode;
#SerializedName("state_id")
#Expose
private Integer stateId;
#SerializedName("city_id")
#Expose
private Integer cityId;
#SerializedName("sechudel")
#Expose
private String sechudel;
#SerializedName("itinerary")
#Expose
private String itinerary;
#SerializedName("edate")
#Expose
private String edate;
#SerializedName("eventimg")
#Expose
private String eventimg;
public Integer getEventId() {
return eventId;
}
public void setEventId(Integer eventId) {
this.eventId = eventId;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getLocationLink() {
return locationLink;
}
public void setLocationLink(String locationLink) {
this.locationLink = locationLink;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public Integer getStateId() {
return stateId;
}
public void setStateId(Integer stateId) {
this.stateId = stateId;
}
public Integer getCityId() {
return cityId;
}
public void setCityId(Integer cityId) {
this.cityId = cityId;
}
public String getSechudel() {
return sechudel;
}
public void setSechudel(String sechudel) {
this.sechudel = sechudel;
}
public String getItinerary() {
return itinerary;
}
public void setItinerary(String itinerary) {
this.itinerary = itinerary;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
public String getEventimg() {
return eventimg;
}
public void setEventimg(String eventimg) {
this.eventimg = eventimg;
}
}
public static class CustomerData implements Serializable {
#SerializedName("customerid")
#Expose
private Integer customerid;
#SerializedName("customername")
#Expose
private String customername;
#SerializedName("gender")
#Expose
private String gender;
#SerializedName("personalcontact")
#Expose
private Integer personalcontact;
#SerializedName("homecontact")
#Expose
private Integer homecontact;
#SerializedName("emailid")
#Expose
private String emailid;
#SerializedName("address")
#Expose
private String address;
#SerializedName("designation")
#Expose
private String designation;
#SerializedName("stateid")
#Expose
private Integer stateid;
#SerializedName("statename")
#Expose
private String statename;
#SerializedName("cityid")
#Expose
private Integer cityid;
#SerializedName("cityname")
#Expose
private String cityname;
#SerializedName("pincode")
#Expose
private Integer pincode;
#SerializedName("birthdate")
#Expose
private String birthdate;
#SerializedName("marriagedate")
#Expose
private String marriagedate;
#SerializedName("category")
#Expose
private String category;
#SerializedName("mdrttick")
#Expose
private Boolean mdrttick;
#SerializedName("profilepicture")
#Expose
private String profilepicture;
#SerializedName("branchname")
#Expose
private String branchname;
#SerializedName("branchcode")
#Expose
private String branchcode;
#SerializedName("licbranchid")
#Expose
private Integer licbranchid;
#SerializedName("division")
#Expose
private String division;
#SerializedName("licdivisionentryid")
#Expose
private Integer licdivisionentryid;
#SerializedName("password")
#Expose
private String password;
#SerializedName("employeename")
#Expose
private String employeename;
#SerializedName("empcontact")
#Expose
private Integer empcontact;
#SerializedName("empmail")
#Expose
private String empmail;
#SerializedName("dealername")
#Expose
private String dealername;
#SerializedName("deacontact")
#Expose
private Integer deacontact;
#SerializedName("deamail")
#Expose
private String deamail;
#SerializedName("club_member")
#Expose
private String clubMember;
#SerializedName("lifeinsurance")
#Expose
private Boolean lifeinsurance;
#SerializedName("nonlife")
#Expose
private Boolean nonlife;
#SerializedName("healthinsurance")
#Expose
private Boolean healthinsurance;
#SerializedName("mutualfunds")
#Expose
private Boolean mutualfunds;
#SerializedName("other")
#Expose
private Boolean other;
#SerializedName("efrom")
#Expose
private String efrom;
#SerializedName("edate")
#Expose
private String edate;
#SerializedName("website")
#Expose
private String website;
#SerializedName("maxdate")
#Expose
private String maxdate;
public Integer getCustomerid() {
return customerid;
}
public void setCustomerid(Integer customerid) {
this.customerid = customerid;
}
public String getCustomername() {
return customername;
}
public void setCustomername(String customername) {
this.customername = customername;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getPersonalcontact() {
return personalcontact;
}
public void setPersonalcontact(Integer personalcontact) {
this.personalcontact = personalcontact;
}
public Integer getHomecontact() {
return homecontact;
}
public void setHomecontact(Integer homecontact) {
this.homecontact = homecontact;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public Integer getStateid() {
return stateid;
}
public void setStateid(Integer stateid) {
this.stateid = stateid;
}
public String getStatename() {
return statename;
}
public void setStatename(String statename) {
this.statename = statename;
}
public Integer getCityid() {
return cityid;
}
public void setCityid(Integer cityid) {
this.cityid = cityid;
}
public String getCityname() {
return cityname;
}
public void setCityname(String cityname) {
this.cityname = cityname;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getMarriagedate() {
return marriagedate;
}
public void setMarriagedate(String marriagedate) {
this.marriagedate = marriagedate;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Boolean getMdrttick() {
return mdrttick;
}
public void setMdrttick(Boolean mdrttick) {
this.mdrttick = mdrttick;
}
public String getProfilepicture() {
return profilepicture;
}
public void setProfilepicture(String profilepicture) {
this.profilepicture = profilepicture;
}
public String getBranchname() {
return branchname;
}
public void setBranchname(String branchname) {
this.branchname = branchname;
}
public String getBranchcode() {
return branchcode;
}
public void setBranchcode(String branchcode) {
this.branchcode = branchcode;
}
public Integer getLicbranchid() {
return licbranchid;
}
public void setLicbranchid(Integer licbranchid) {
this.licbranchid = licbranchid;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public Integer getLicdivisionentryid() {
return licdivisionentryid;
}
public void setLicdivisionentryid(Integer licdivisionentryid) {
this.licdivisionentryid = licdivisionentryid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmployeename() {
return employeename;
}
public void setEmployeename(String employeename) {
this.employeename = employeename;
}
public Integer getEmpcontact() {
return empcontact;
}
public void setEmpcontact(Integer empcontact) {
this.empcontact = empcontact;
}
public String getEmpmail() {
return empmail;
}
public void setEmpmail(String empmail) {
this.empmail = empmail;
}
public String getDealername() {
return dealername;
}
public void setDealername(String dealername) {
this.dealername = dealername;
}
public Integer getDeacontact() {
return deacontact;
}
public void setDeacontact(Integer deacontact) {
this.deacontact = deacontact;
}
public String getDeamail() {
return deamail;
}
public void setDeamail(String deamail) {
this.deamail = deamail;
}
public String getClubMember() {
return clubMember;
}
public void setClubMember(String clubMember) {
this.clubMember = clubMember;
}
public Boolean getLifeinsurance() {
return lifeinsurance;
}
public void setLifeinsurance(Boolean lifeinsurance) {
this.lifeinsurance = lifeinsurance;
}
public Boolean getNonlife() {
return nonlife;
}
public void setNonlife(Boolean nonlife) {
this.nonlife = nonlife;
}
public Boolean getHealthinsurance() {
return healthinsurance;
}
public void setHealthinsurance(Boolean healthinsurance) {
this.healthinsurance = healthinsurance;
}
public Boolean getMutualfunds() {
return mutualfunds;
}
public void setMutualfunds(Boolean mutualfunds) {
this.mutualfunds = mutualfunds;
}
public Boolean getOther() {
return other;
}
public void setOther(Boolean other) {
this.other = other;
}
public String getEfrom() {
return efrom;
}
public void setEfrom(String efrom) {
this.efrom = efrom;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getMaxdate() {
return maxdate;
}
public void setMaxdate(String maxdate) {
this.maxdate = maxdate;
}
}
}
Expected BEGIN_ARRAY but was String at line 1 column 61 . $ customer.Data
Customer_Event is Arraylist
#SerializedName("Customer_Event")
#Expose
private List<CustomerEvent> customerEvent = null;
Gson Library expecting the Array first not the Object. there is nothing wrong in your code. but need to modify the JSON Structure here.
Try using this structure :
Note rootArray is starting point/ is used for your reference
rootArray[
// object
{
"Key": value,
"Key": value,
"Key": value
}
// array1
"Customer_Data":[
{
"Key": value,
"Key": value,
"Key": value
}
],
// array 2
"All_Event": [
{
"Key": value,
"Key": value,
"Key": value
}
]
]

Why i'm getting expected begin_array but was String

This is my json data
{
"Success": true,
"Message": "User Not Found",
"Customer_Data": "",
"Customer_Device": "",
"Customer_Event": "",
"All_Event": [
{
"event_id": 6,
"event_name": "Test Event - 1",
"start_date": "01/06/2019",
"end_date": "01/06/2019",
"address_1": "Mumbai",
"address_2": "Mumbai",
"location_link": "https://goo.gl/maps/vTia6DQxwmiA5kvz6",
"pincode": 400060,
"state_id": 10,
"city_id": 355,
"sechudel": "Test",
"itinerary": "Test",
"edate": "2019-05-09T17:00:05.95592",
"eventimg": "http://zaidicorp.in/login/ProcessImage/636935218388448729.png"
}
],
"Status": 1,
"Currentdate": "5/16/2019 11:40:54 AM"
}
this is my pojo file
package mytraining.com.mytraining.Pojo;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
public class OtpCheck implements Serializable {
#SerializedName("Success")
#Expose
private Boolean success;
#SerializedName("Message")
#Expose
private String message;
#SerializedName("Customer_Data")
#Expose
private List<CustomerData> customerData;
#SerializedName("Customer_Device")
#Expose
private List<CustomerDevice> customerDevice;
#SerializedName("Customer_Event")
#Expose
private List<CustomerEvent> customerEvent;
#SerializedName("Event")
#Expose
private List<EventDetail> eventDetails;
#SerializedName("Status")
#Expose
private Integer status;
#SerializedName("Currentdate")
#Expose
private String currentdate;
public List<EventDetail> getEventDetails() {
return eventDetails;
}
public void setEventDetails(List<EventDetail> eventDetails) {
this.eventDetails = eventDetails;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<CustomerData> getCustomerData() {
return customerData;
}
public void setCustomerData(List<CustomerData> customerData) {
this.customerData = customerData;
}
public List<CustomerDevice> getCustomerDevice() {
return customerDevice;
}
public void setCustomerDevice(List<CustomerDevice> customerDevice) {
this.customerDevice = customerDevice;
}
public List<CustomerEvent> getCustomerEvent() {
return customerEvent;
}
public void setCustomerEvent(List<CustomerEvent> customerEvent) {
this.customerEvent = customerEvent;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCurrentdate() {
return currentdate;
}
public void setCurrentdate(String currentdate) {
this.currentdate = currentdate;
}
/**
* Inner Class For Customer Data
*/
public static class CustomerData implements Serializable {
#SerializedName("cust_id")
#Expose
private Integer custId;
#SerializedName("cust_email")
#Expose
private String custEmail;
#SerializedName("customername")
#Expose
private String customername;
#SerializedName("personalcontact")
#Expose
private String personalcontact;
public Integer getCustId() {
return custId;
}
public void setCustId(Integer custId) {
this.custId = custId;
}
public String getCustEmail() {
return custEmail;
}
public void setCustEmail(String custEmail) {
this.custEmail = custEmail;
}
public String getCustomername() {
return customername;
}
public void setCustomername(String customername) {
this.customername = customername;
}
public String getPersonalcontact() {
return personalcontact;
}
public void setPersonalcontact(String personalcontact) {
this.personalcontact = personalcontact;
}
}
/**
* Inner Class For Customer Device
*/
public static class CustomerDevice implements Serializable {
#SerializedName("cust_id")
#Expose
private Integer custId;
#SerializedName("Cust_device")
#Expose
private String custDevice;
#SerializedName("bg_device_Brand")
#Expose
private String bgDeviceBrand;
#SerializedName("bg_device_model")
#Expose
private String bgDeviceModel;
#SerializedName("android_ver")
#Expose
private String androidVer;
#SerializedName("device_mac")
#Expose
private String deviceMac;
#SerializedName("opt")
#Expose
private Object opt;
public Integer getCustId() {
return custId;
}
public void setCustId(Integer custId) {
this.custId = custId;
}
public String getCustDevice() {
return custDevice;
}
public void setCustDevice(String custDevice) {
this.custDevice = custDevice;
}
public String getBgDeviceBrand() {
return bgDeviceBrand;
}
public void setBgDeviceBrand(String bgDeviceBrand) {
this.bgDeviceBrand = bgDeviceBrand;
}
public String getBgDeviceModel() {
return bgDeviceModel;
}
public void setBgDeviceModel(String bgDeviceModel) {
this.bgDeviceModel = bgDeviceModel;
}
public String getAndroidVer() {
return androidVer;
}
public void setAndroidVer(String androidVer) {
this.androidVer = androidVer;
}
public String getDeviceMac() {
return deviceMac;
}
public void setDeviceMac(String deviceMac) {
this.deviceMac = deviceMac;
}
public Object getOpt() {
return opt;
}
public void setOpt(Object opt) {
this.opt = opt;
}
}
/**
* Inner Class For Customer Event
*/
public static class CustomerEvent implements Serializable {
#SerializedName("ticket_no")
#Expose
private String ticketNo;
#SerializedName("seat_no")
#Expose
private String seatNo;
#SerializedName("event_name")
#Expose
private String eventName;
#SerializedName("start_date")
#Expose
private String startDate;
#SerializedName("end_date")
#Expose
private String endDate;
#SerializedName("location_link")
#Expose
private String locationLink;
#SerializedName("edate")
#Expose
private String edate;
public String getTicketNo() {
return ticketNo;
}
public void setTicketNo(String ticketNo) {
this.ticketNo = ticketNo;
}
public String getSeatNo() {
return seatNo;
}
public void setSeatNo(String seatNo) {
this.seatNo = seatNo;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getLocationLink() {
return locationLink;
}
public void setLocationLink(String locationLink) {
this.locationLink = locationLink;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
}
/**
* Inner Class For Event Detail
*/
public static class EventDetail implements Serializable {
#SerializedName("event_id")
#Expose
private Integer eventId;
#SerializedName("event_name")
#Expose
private String eventName;
#SerializedName("start_date")
#Expose
private String startDate;
#SerializedName("end_date")
#Expose
private String endDate;
#SerializedName("address_1")
#Expose
private String address1;
#SerializedName("address_2")
#Expose
private String address2;
#SerializedName("location_link")
#Expose
private String locationLink;
#SerializedName("pincode")
#Expose
private Integer pincode;
#SerializedName("state_id")
#Expose
private Integer stateId;
#SerializedName("city_id")
#Expose
private Integer cityId;
#SerializedName("sechudel")
#Expose
private String sechudel;
#SerializedName("itinerary")
#Expose
private String itinerary;
#SerializedName("edate")
#Expose
private String edate;
#SerializedName("eventimg")
#Expose
private String eventimg;
public Integer getEventId() {
return eventId;
}
public void setEventId(Integer eventId) {
this.eventId = eventId;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getLocationLink() {
return locationLink;
}
public void setLocationLink(String locationLink) {
this.locationLink = locationLink;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public Integer getStateId() {
return stateId;
}
public void setStateId(Integer stateId) {
this.stateId = stateId;
}
public Integer getCityId() {
return cityId;
}
public void setCityId(Integer cityId) {
this.cityId = cityId;
}
public String getSechudel() {
return sechudel;
}
public void setSechudel(String sechudel) {
this.sechudel = sechudel;
}
public String getItinerary() {
return itinerary;
}
public void setItinerary(String itinerary) {
this.itinerary = itinerary;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
public String getEventimg() {
return eventimg;
}
public void setEventimg(String eventimg) {
this.eventimg = eventimg;
}
}
}
this my is java calling class
private void eventDetial(Map<String, String> map) {
Call<OtpCheck> call = apiInterface.eventShow(map);
call.enqueue(new Callback<OtpCheck>() {
#Override
public void onResponse(Call<OtpCheck> call, Response<OtpCheck> response) {
List<OtpCheck.EventDetail> data = response.body().getEventDetails();
for (int i = 0; i < 1; i++) {
image = data.get(i).getEventimg();
Log.i("Data", "data");
Glide.with(getActivity()).load(image).into(imageView);
}
}
#Override
public void onFailure(Call<OtpCheck> call, Throwable t) {
Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
I tried multiple ways from StackOverflow but still not getting error
expected begin_array but was String
Firstly got Error from below field, this 3 field is String but you set ArrayList. But it will be String. Like below.
"Customer_Data": "",
"Customer_Device": "",
"Customer_Event": "",
#SerializedName("Customer_Data")
#Expose
private String customerData;
#SerializedName("Customer_Device")
#Expose
private String customerDevice;
#SerializedName("Customer_Event")
#Expose
private String customerEvent;
Also, Have no any event field. so need change from
#SerializedName("Event")
#Expose
private List<EventDetail> eventDetails;
To
#SerializedName("All_Event")
#Expose
private List<EventDetail> eventDetails;
Your problem is in your #SerializedName:
#SerializedName("Event")
#Expose
private List<EventDetail> eventDetails;
The tag SerializedName must have the name of the element of the json. Then you must changue it for:
#SerializedName("All_Event")
#Expose
private List<EventDetail> eventDetails;

How do I deserialize a nested JSON array using GSON?

Here's an example of my JSON:
{
"status": "ok",
"rowCount": 60,
"pageCount": 6,
"value": [{
"CustomerID": 1911,
"CustomerTypeID": 3,
...
}
]
}
My POJO:
#SerializedName("CustomerID")
public Integer CustomerID;
#SerializedName("CustomerTypeID")
public Integer CustomerTypeID;
I want to pull everything under value.
How do I do this using Google's GSON?
I've tried doing it as I would normally, but for, obvious reasons, it didn't work:
Type collectionType = new TypeToken<ArrayList<Customer>>() {}.getType();
return gson.fromJson(json, collectionType);
You can not skip root JSON object. The simplest solution in this case is - create root POJO:
class Response {
#SerializedName("value")
private List<Customer> customers;
// getters, setters
}
And you can use it as below:
return gson.fromJson(json, Response.class).getCustomers();
You don't need to worry writing your own POJO.
just visit http://www.jsonschema2pojo.org/
and paste here your JSON data, it'll automatically return you converted classes as below
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("status")
#Expose
private String status;
#SerializedName("rowCount")
#Expose
private Integer rowCount;
#SerializedName("pageCount")
#Expose
private Integer pageCount;
#SerializedName("value")
#Expose
private List<Value> value = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getRowCount() {
return rowCount;
}
public void setRowCount(Integer rowCount) {
this.rowCount = rowCount;
}
public Integer getPageCount() {
return pageCount;
}
public void setPageCount(Integer pageCount) {
this.pageCount = pageCount;
}
public List<Value> getValue() {
return value;
}
public void setValue(List<Value> value) {
this.value = value;
}
}
-----------------------------------com.example.Value.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Value {
#SerializedName("CustomerID")
#Expose
private Integer customerID;
#SerializedName("CustomerTypeID")
#Expose
private Integer customerTypeID;
public Integer getCustomerID() {
return customerID;
}
public void setCustomerID(Integer customerID) {
this.customerID = customerID;
}
public Integer getCustomerTypeID() {
return customerTypeID;
}
public void setCustomerTypeID(Integer customerTypeID) {
this.customerTypeID = customerTypeID;
}
}
The above two classes are auto generated by website.
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ExampleClass {
#SerializedName("status")
#Expose
private String status;
#SerializedName("rowCount")
#Expose
private int rowCount;
#SerializedName("pageCount")
#Expose
private int pageCount;
#SerializedName("value")
#Expose
private List<Value> value = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getRowCount() {
return rowCount;
}
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public List<Value> getValue() {
return value;
}
public void setValue(List<Value> value) {
this.value = value;
}
}
-----------------------------------Value.java-----------------------------------
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Value {
#SerializedName("CustomerID")
#Expose
private int customerID;
#SerializedName("CustomerTypeID")
#Expose
private int customerTypeID;
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public int getCustomerTypeID() {
return customerTypeID;
}
public void setCustomerTypeID(int customerTypeID) {
this.customerTypeID = customerTypeID;
}
}
/********* parsing with Gson ******/
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
ExampleClass resultObj = gson.fromJson(jsonObject.toString(), ExampleClass.class);
List<Value> yourListOfCustomerValues = resultObj.getValue();
You can refer to this amazing post on mapping of arrays and lists of objects with Gson by Norman Peitek
Basics of Gson, model annotations and mapping of nested objects

Java JSON Parse literal string

I'm making Java Application which runs with C++ Server and want to receive a JSON Object from the server. Basiclly I'm sending LatLng(Latitude, Longtitude) to the server and it's returning me elements from the Google Maps API, but the problem is that the return elements have escape characters in them and I can't parse them with JSONObject.
#Override
protected void onPostExecute(string output) {
super.onPostExecute(output);
try {
JSONObject data = new JSONObject(output);
String test = data.getJSONObject("main_Points").getString("name");
System.out.print(test);
} catch(Exception ex) {
ex.printStackTrace();
}
}
And here's my JSON Object (Error:org.json.JSONException: Unterminated object at character 579)
{
"main_Points":{
"final":{
"lat":42.502812,
"lng":27.4691601,
"name":"бул. „Сан Стефано“ 62, 8001 ж.к. Братя Миладинови, Бургас, България"
},
"start":{
"lat":42.4912504,
"lng":27.4725683,
"name":"бул. „Иван Вазов“ 1, 8000 Бургас Център, Бургас, България"
}
},
"nearestPoints":{
"final":{
"lat":42.503294,
"lng":27.468482,
"name":"БСУ"
},
"start":{
"lat":42.490604,
"lng":27.474128,
"name":"Автогара Юг"
}
},
"polylines":{
"final":"qilbGgatfDR`Bo#?eA\\",
"middle":"}|ibGi`ufD#~#Ah#MVGMwB`##bCG~CeFtBiBr#yApAeBl#sBr#aDbAiC|#cCr#uJfCaDz#{ElAoCl#OC_B^}Bh#Gm#m#cF_A#eA\\",
"start":"iajbGqvtfDAaDvBa#FLLW#i#A_A"
}
}
You can create object from json string with :
http://www.jsonschema2pojo.org/
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("main_Points")
#Expose
private MainPoints mainPoints;
#SerializedName("nearestPoints")
#Expose
private NearestPoints nearestPoints;
#SerializedName("polylines")
#Expose
private Polylines polylines;
public MainPoints getMainPoints() {
return mainPoints;
}
public void setMainPoints(MainPoints mainPoints) {
this.mainPoints = mainPoints;
}
public NearestPoints getNearestPoints() {
return nearestPoints;
}
public void setNearestPoints(NearestPoints nearestPoints) {
this.nearestPoints = nearestPoints;
}
public Polylines getPolylines() {
return polylines;
}
public void setPolylines(Polylines polylines) {
this.polylines = polylines;
}
}
-----------------------------------com.example.Final.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Final {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lng")
#Expose
private Double lng;
#SerializedName("name")
#Expose
private String name;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLng() {
return lng;
}
public void setLng(Double lng) {
this.lng = lng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
-----------------------------------com.example.Final_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Final_ {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lng")
#Expose
private Double lng;
#SerializedName("name")
#Expose
private String name;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLng() {
return lng;
}
public void setLng(Double lng) {
this.lng = lng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
-----------------------------------com.example.MainPoints.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MainPoints {
#SerializedName("final")
#Expose
private Final _final;
#SerializedName("start")
#Expose
private Start start;
public Final getFinal() {
return _final;
}
public void setFinal(Final _final) {
this._final = _final;
}
public Start getStart() {
return start;
}
public void setStart(Start start) {
this.start = start;
}
}
-----------------------------------com.example.NearestPoints.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NearestPoints {
#SerializedName("final")
#Expose
private Final_ _final;
#SerializedName("start")
#Expose
private Start_ start;
public Final_ getFinal() {
return _final;
}
public void setFinal(Final_ _final) {
this._final = _final;
}
public Start_ getStart() {
return start;
}
public void setStart(Start_ start) {
this.start = start;
}
}
-----------------------------------com.example.Polylines.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Polylines {
#SerializedName("final")
#Expose
private String _final;
#SerializedName("middle")
#Expose
private String middle;
#SerializedName("start")
#Expose
private String start;
public String getFinal() {
return _final;
}
public void setFinal(String _final) {
this._final = _final;
}
public String getMiddle() {
return middle;
}
public void setMiddle(String middle) {
this.middle = middle;
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
}
-----------------------------------com.example.Start.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Start {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lng")
#Expose
private Double lng;
#SerializedName("name")
#Expose
private String name;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLng() {
return lng;
}
public void setLng(Double lng) {
this.lng = lng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
-----------------------------------com.example.Start_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Start_ {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lng")
#Expose
private Double lng;
#SerializedName("name")
#Expose
private String name;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLng() {
return lng;
}
public void setLng(Double lng) {
this.lng = lng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And
#Override
protected void onPostExecute(string output) {
super.onPostExecute(output);
try {
JSONObject data = new JSONObject(output);
Gson g = new Gson();
Example example = g.fromJson(data.toString(), Example.class);
} catch(Exception ex) {
ex.printStackTrace();
}
}
You will get everything in Example object.
I hope it will help your problem!

How to iterate key-value pair in Retrofit

I am having trouble parsing the below JSON structure. Basically I have to read the values object as list but the server returns as a JsonObject and the value changes based on the totalPageCount. Is there any way I can read the values as List? Should I use reflections ? Currently I am using Retrofit with returns the model class.
Any help is really appreciated.
Thank you
{
"page" : 0,
"pageSize" : 10,
"totalPageCount" : 1,
"values" : {
"key1" : "value1",
"key2" : "value2",
"key3" : "value3",
"key4" : "value4",
}
}
Model class :
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("page")
#Expose
private Integer page;
#SerializedName("pageSize")
#Expose
private Integer pageSize;
#SerializedName("totalPageCount")
#Expose
private Integer totalPageCount;
#SerializedName("values")
#Expose
private Values values;
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalPageCount() {
return totalPageCount;
}
public void setTotalPageCount(Integer totalPageCount) {
this.totalPageCount = totalPageCount;
}
public Values getValues() {
return values;
}
public void setValues(Values values) {
this.values = values;
}
}
-----------------------------------com.example.Values.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Values {
#SerializedName("key1")
#Expose
private String key1;
#SerializedName("key2")
#Expose
private String key2;
#SerializedName("key3")
#Expose
private String key3;
#SerializedName("key4")
#Expose
private String key4;
public String getKey1() {
return key1;
}
public void setKey1(String key1) {
this.key1 = key1;
}
public String getKey2() {
return key2;
}
public void setKey2(String key2) {
this.key2 = key2;
}
public String getKey3() {
return key3;
}
public void setKey3(String key3) {
this.key3 = key3;
}
public String getKey4() {
return key4;
}
public void setKey4(String key4) {
this.key4 = key4;
}
}
This will work
private Map<String,String> values;

Categories