How do I deserialize a nested JSON array using GSON? - java

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

Related

how to retrieve data from api on java android and use it?

Hi everybody and thanks for helping me,
I'm trying to fetch data from an api url "https://api.stackexchange.com/2.2/search?order=desc&sort=creation&site=stackoverflow&tagged=android" and I don't know what I am missing.
I keep on getting an error saying that I am pointing to a null object, but it is not supposed to be null.
That is the error message
`
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.finalhomework, PID: 5005
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
at com.example.finalhomework.view.SearchActivity$1.onResponse(SearchActivity.java:46)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:89)
at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$3wC8FyV4pyjrzrYL5U0mlYiviZw.run(lambda)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)`
That is the results page which is supposed to get all the item
`
package com.example.finalhomework.model;
import java.io.Serializable;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class StackOverflowPageResult implements Serializable
{
#SerializedName("StackOverflowItem")
#Expose
private List<StackOverflowItem> items = null;
#SerializedName("has_more")
#Expose
private Boolean hasMore;
#SerializedName("quota_max")
#Expose
private Integer quotaMax;
#SerializedName("quota_remaining")
#Expose
private Integer quotaRemaining;
private final static long serialVersionUID = -263378404000205617L;
public List<StackOverflowItem> getStackOverflowItem() {
return items;
}
public void setItems(List<StackOverflowItem> items) {
this.items = items;
}
public Boolean getHasMore() {
return hasMore;
}
public void setHasMore(Boolean hasMore) {
this.hasMore = hasMore;
}
public Integer getQuotaMax() {
return quotaMax;
}
public void setQuotaMax(Integer quotaMax) {
this.quotaMax = quotaMax;
}
public Integer getQuotaRemaining() {
return quotaRemaining;
}
public void setQuotaRemaining(Integer quotaRemaining) {
this.quotaRemaining = quotaRemaining;
}
}`
That is the Item itself:
`
package com.example.finalhomework.model;
import java.io.Serializable;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class StackOverflowItem implements Serializable
{
#SerializedName("tags")
#Expose
private List<String> tags = null;
#SerializedName("owner")
#Expose
private Owner owner;
#SerializedName("is_answered")
#Expose
private Boolean isAnswered;
#SerializedName("view_count")
#Expose
private Integer viewCount;
#SerializedName("answer_count")
#Expose
private Integer answerCount;
#SerializedName("score")
#Expose
private Integer score;
#SerializedName("last_activity_date")
#Expose
private Integer lastActivityDate;
#SerializedName("creation_date")
#Expose
private Integer creationDate;
#SerializedName("question_id")
#Expose
private Integer questionId;
#SerializedName("content_license")
#Expose
private String contentLicense;
#SerializedName("link")
#Expose
private String link;
#SerializedName("title")
#Expose
private String title;
#SerializedName("last_edit_date")
#Expose
private Integer lastEditDate;
#SerializedName("accepted_answer_id")
#Expose
private Integer acceptedAnswerId;
#SerializedName("closed_date")
#Expose
private Integer closedDate;
#SerializedName("closed_reason")
#Expose
private String closedReason;
private final static long serialVersionUID = 2088551364601451752L;
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public Boolean getIsAnswered() {
return isAnswered;
}
public void setIsAnswered(Boolean isAnswered) {
this.isAnswered = isAnswered;
}
public Integer getViewCount() {
return viewCount;
}
public void setViewCount(Integer viewCount) {
this.viewCount = viewCount;
}
public Integer getAnswerCount() {
return answerCount;
}
public void setAnswerCount(Integer answerCount) {
this.answerCount = answerCount;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public Integer getLastActivityDate() {
return lastActivityDate;
}
public void setLastActivityDate(Integer lastActivityDate) {
this.lastActivityDate = lastActivityDate;
}
public Integer getCreationDate() {
return creationDate;
}
public void setCreationDate(Integer creationDate) {
this.creationDate = creationDate;
}
public Integer getQuestionId() {
return questionId;
}
public void setQuestionId(Integer questionId) {
this.questionId = questionId;
}
public String getContentLicense() {
return contentLicense;
}
public void setContentLicense(String contentLicense) {
this.contentLicense = contentLicense;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getLastEditDate() {
return lastEditDate;
}
public void setLastEditDate(Integer lastEditDate) {
this.lastEditDate = lastEditDate;
}
public Integer getAcceptedAnswerId() {
return acceptedAnswerId;
}
public void setAcceptedAnswerId(Integer acceptedAnswerId) {
this.acceptedAnswerId = acceptedAnswerId;
}
public Integer getClosedDate() {
return closedDate;
}
public void setClosedDate(Integer closedDate) {
this.closedDate = closedDate;
}
public String getClosedReason() {
return closedReason;
}
public void setClosedReason(String closedReason) {
this.closedReason = closedReason;
}
}`
That is the Retrofit builder with the url:
`
package com.example.finalhomework.network;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitInstance {
private static Retrofit retrofit;
private static final String BASE_URL ="https://api.stackexchange.com/2.2/";
public static Retrofit getRetrofitInstance(){
if (retrofit == null){
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}`
That is the interface with the url's arguments:
`
package com.example.finalhomework.network;
import com.example.finalhomework.model.StackOverflowPageResult;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface GetStackOverflowItemDataService {
#GET("search")
Call<StackOverflowPageResult> getStackOverflowItem(
#Query("tagged") String tagged,
#Query("site") String site,
#Query("sort") String sort,
#Query("order") String order
);
}`
And here we've got the class which is supposed to get the total result, and I put a Log.i in order to check if everything is in order and the stackOverflowItems is null:
`
package com.example.finalhomework.view;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
import android.util.Log;
import com.example.finalhomework.R;
import com.example.finalhomework.model.StackOverflowItem;
import com.example.finalhomework.model.StackOverflowPageResult;
import com.example.finalhomework.network.GetStackOverflowItemDataService;
import com.example.finalhomework.network.RetrofitInstance;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class SearchActivity extends AppCompatActivity {
Toolbar toolbar;
private GetStackOverflowItemDataService stackOverflowItemDataService;
List<StackOverflowItem> stackOverflowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
setToolbarBack();
stackOverflowItemDataService = RetrofitInstance.getRetrofitInstance().create(GetStackOverflowItemDataService.class);
stackOverflowItemDataService.getStackOverflowItem("android", "stackoverflow", "creation", "desc")
.enqueue(new Callback<StackOverflowPageResult>() {
#Override
public void onResponse(Call<StackOverflowPageResult> call, Response<StackOverflowPageResult> response) {
StackOverflowPageResult stackOverflowPageResult = response.body();
stackOverflowItems = stackOverflowPageResult.getStackOverflowItem();
for (StackOverflowItem s : stackOverflowItems) {
Log.i("Item StackOverflow :", s.getTitle());
}
}
#Override
public void onFailure(Call<StackOverflowPageResult> call, Throwable t) {
}
});
}`
Again thanks for the help
There is mismatch between JSON data variable and your #SerializedName("StackOverflowItem")
So make the changes to match the SerializedName, code as follows -
public class StackOverflowPageResult implements Serializable {
#SerializedName("items")
private List<StackOverflowItem> items;
#SerializedName("has_more")
private Boolean hasMore;
#SerializedName("quota_max")
private Integer quotaMax;
#SerializedName("quota_remaining")
private Integer quotaRemaining;
// your further code here
//.............
}
SerializedName is only required when you are going to take variable name different from JSON object, otherwise you can skip #SerializedName tag as well.
One more thing I suggest, I you are not going to call excludeFieldsWithoutExposeAnnotation() in your GsonBuilder class, then there is no need for #Expose tag.
The Gson #Expose annotation can be used to mark a field to be exposed or not (included or not) for serialized or deserialized. The #Expose annotation can take two parameters and each parameter is a boolean which can take either the value true or false. In order to get GSON to react to the #Expose annotations we must create a Gson instance using the GsonBuilder class and need to call the excludeFieldsWithoutExposeAnnotation() method, it configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation.
Happy Coding !

Parsing Json data. Nested Objects giving an error

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"));

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;

Java class from json with same name

I have a JSON object like the following:
...
{
"url": "checkout.bodenusa.com/en-US"
},
{
"url": [
".bonton.com/checkout/",
".bonton.com/CheckoutView"
]
}
...
How should my Java class look like for Response server.
I try this snippet, but it is incorrect:
#SerializedName("url")
#Expose
private List<String> urlList = null;
#SerializedName("url")
#Expose
private String url;
Create a model like
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Model {
#SerializedName("url")
#Expose
private List<String> url = null;
#SerializedName("apply")
#Expose
private Apply apply;
#SerializedName("controls")
#Expose
private Controls controls;
#SerializedName("remove")
#Expose
private Remove remove;
public List<String> getUrl() {
return url;
}
public void setUrl(List<String> url) {
this.url = url;
}
public Apply getApply() {
return apply;
}
public void setApply(Apply apply) {
this.apply = apply;
}
public Controls getControls() {
return controls;
}
public void setControls(Controls controls) {
this.controls = controls;
}
public Remove getRemove() {
return remove;
}
public void setRemove(Remove remove) {
this.remove = remove;
}
public class Controls {
#SerializedName("promo")
#Expose
private String promo;
#SerializedName("total")
#Expose
private String total;
#SerializedName("orderTotal")
#Expose
private String orderTotal;
#SerializedName("coupon")
#Expose
private String coupon;
public String getPromo() {
return promo;
}
public void setPromo(String promo) {
this.promo = promo;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getOrderTotal() {
return orderTotal;
}
public void setOrderTotal(String orderTotal) {
this.orderTotal = orderTotal;
}
public String getCoupon() {
return coupon;
}
public void setCoupon(String coupon) {
this.coupon = coupon;
}
}
public class Remove {
#SerializedName("type")
#Expose
private String type;
#SerializedName("submit")
#Expose
private String submit;
#SerializedName("timeout")
#Expose
private Integer timeout;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSubmit() {
return submit;
}
public void setSubmit(String submit) {
this.submit = submit;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
}
public class Apply {
#SerializedName("type")
#Expose
private String type;
#SerializedName("submit")
#Expose
private String submit;
#SerializedName("timeout")
#Expose
private Integer timeout;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSubmit() {
return submit;
}
public void setSubmit(String submit) {
this.submit = submit;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
}
}
Use this class along with a Custom TypeAdapter for Gson .Then it will work for both List and Object response .
ArrayAdapter class
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
public class ArrayAdapterFactory implements TypeAdapterFactory {
#Override
#SuppressWarnings({"unchecked", "rawtypes"})
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
TypeAdapter<T> typeAdapter = null;
try {
if (type.getRawType() == List.class || type.getRawType() == ArrayList.class) {
typeAdapter = new ArrayAdapter(gson,
(Class) ((ParameterizedType) type.getType())
.getActualTypeArguments()[0]);
}
} catch (Exception e) {
e.printStackTrace();
}
return typeAdapter;
}
}
ArrayAdapterFactory class
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class ArrayAdapter<T> extends TypeAdapter<List<T>> {
private Class<T> adapterclass;
private Gson gson;
public ArrayAdapter(Gson gson, Class<T> adapterclass) {
this.adapterclass = adapterclass;
this.gson = gson;
}
#Override
public List<T> read(JsonReader reader) throws IOException {
List<T> list = new ArrayList<T>();
final JsonToken token = reader.peek();
System.out.println(token);
// Handling of Scenario 2( Check JavaDoc for the class) :
if (token == JsonToken.STRING || token == JsonToken.NUMBER ||
token == JsonToken.BOOLEAN) {
T inning = (T) gson.fromJson(reader, adapterclass);
list.add(inning);
} else if (token == JsonToken.BEGIN_OBJECT) {
// Handling of Scenario 1(Check JavaDoc for the class) :
T inning = (T) gson.fromJson(reader, adapterclass);
list.add(inning);
} else if (token == JsonToken.BEGIN_ARRAY) {
reader.beginArray();
while (reader.hasNext()) {
#SuppressWarnings("unchecked")
T inning = (T) gson.fromJson(reader, adapterclass);
list.add(inning);
}
reader.endArray();
}
return list;
}
#Override
public void write(JsonWriter writer, List<T> value) throws IOException {
}
}
And register the adapter factory like this,
Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();
public class Example {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Use this link to generate POJO's

want to deserialize json string into java object with arraylist

java object: MyObject has a list of AnotherObject1 and AnotherObject1 also have a list of AnotherObject2
class MyObject{
private String status;
private String message;
private List<AnotherObject1> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<AnotherObject1> getData() {
return data;
}
public void setData(List<AnotherObject1> data) {
this.data = data;
}
}
Class AnotherObject1{
private Integer group_id;
private List<AnotherObject2> anotherList;
public Integer getGroup_id() {
return group_id;
}
public void setGroup_id(Integer group_id) {
this.group_id = group_id;
}
public List<AnotherObject2> getAnotherList() {
return smsList;
}
public void setAnotherList(List<AnotherObject2> anotherList) {
this.anotherList = anotherList;
}
}
class AnotherObject2{
private String customid;
private String customid1 ;
private Long mobile;
private String status;
private String country;
public String getCustomid() {
return customid;
}
public void setCustomid(String customid) {
this.customid = customid;
}
public String getCustomid1() {
return customid1;
}
public void setCustomid1(String customid1) {
this.customid1 = customid1;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
JSON String: this is my json string by which i want to make an java object using object mapper
String response="{\"status\":\"OK\",\"data\":{\"group_id\":39545922,\"0\":{\"id\":\"39545922-1\",\"customid\":\"\",\"customid1\":\"\",\"customid2\":\"\",\"mobile\":\"910123456789\",\"status\":\"XYZ\",\"country\":\"IN\"}},\"message\":\"WE R Happy.\"}"
ObjectMapper code
//convert string to response object
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.readValue(responseBody, MyObject.class);
exception: here is the exception
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: {"status":"OK","data":{"group_id":39545922,"0":{"id":"39545922-1","customid":"","customid1":"","customid2":"","mobile":"910123456789","status":"GOOD","country":"IN"}},"message":"We R happy."}; line: 1, column: 15] (through reference chain: MyObject["data"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:854)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:850)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:292)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:227)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:217)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:25)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:520)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:256)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3702)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2714)
at abc.disp(RestClientImpl.java:210)
at abc.disp(RestClientImpl.java:105)
at Application.<init>(Application.java:42)
at Application.main(Application.java:45)
please guide me how to make it possible.
Your code itself is not compailable ...
private List<AnotherObject1> data; // Your class member is list of AnotherObject1
and below it is used as List of SMSDTO in getter and setter
public List<SMSDTO> getData() {
return data;
}
Problem is quite simple: you claim data should become Java List; and this requires that JSON input for it should be JSON Array. But what JSON instead has is a JSON Object.
So you either need to change POJO definition to expect something compatible with JSON Object (a POJO or java.util.Map); or JSON to contain an array for data.
First as Naveen Ramawat said your code is not compilable as it is.
In the class AnotherObject1 getSmsList should take AnotherObject2 and setSmsList should take AnotherObject2 also as parameter.
In the class MyObject setData and getData should use AnotherObject1 as parameters
Second your JSON string is not valid it should be sommething like that:
{"status":"OK","data":[{"group_id":39545922,"smsList":[{"customid":"39545922-1","customid1":"","mobile":913456789,"status":"XYZ","country":"XYZ"}]}]}
Here is the code that I used :
MyObject.java:
import java.util.List;
class MyObject {
private String status;
private String message;
private List<AnotherObject1> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<AnotherObject1> getData() {
return data;
}
public void setData(List<AnotherObject1> data) {
this.data = data;
}
}
AnotherObject1.java :
import java.util.List;
public class AnotherObject1 {
private Integer group_id;
private List<AnotherObject2> smsList;
public Integer getGroup_id() {
return group_id;
}
public void setGroup_id(Integer group_id) {
this.group_id = group_id;
}
public List<AnotherObject2> getSmsList() {
return smsList;
}
public void setSmsList(List<AnotherObject2> smsList) {
this.smsList = smsList;
}
}
AnotherObject2.java :
public class AnotherObject2 {
private String customid;
private String customid1;
private Long mobile;
private String status;
private String country;
public String getCustomid() {
return customid;
}
public void setCustomid(String customid) {
this.customid = customid;
}
public String getCustomid1() {
return customid1;
}
public void setCustomid1(String customid1) {
this.customid1 = customid1;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
To get the JSON string :
import org.json.JSONObject;
import org.json.XML;
import com.google.gson.Gson;
MyObject myObj = new MyObject();
ArrayList<AnotherObject2> smsList = new ArrayList<AnotherObject2>();
ArrayList<AnotherObject1> data = new ArrayList<AnotherObject1>();
AnotherObject1 ao1 = new AnotherObject1();
ao1.setGroup_id(39545922);
ao1.setSmsList(smsList);
AnotherObject2 sms = new AnotherObject2();
sms.setCountry("XYZ");
sms.setCustomid("39545922-1");
sms.setCustomid1("");
sms.setMobile((long) 913456789);
sms.setStatus("XYZ");
smsList.add(sms);
ao1.setSmsList(smsList);
data.add(ao1);
myObj.setStatus("OK");
myObj.setData(data);
// Build a JSON string to display
Gson gson = new Gson();
String jsonString = gson.toJson(myObj);
System.out.println(jsonString);
// Get an object from a JSON string
MyObject myObject2 = gson.fromJson(jsonString, MyObject.class);
// Display the new object
System.out.println(gson.toJson(myObject2));

Categories