I am getting JSON Object when their is only one response(Plan) and JSON Array when their is more than one response(plan).How to handle JSON Response?
JSON ARRAY when their is more than one plan.
{
"ocrNumber": "0123456",
"userName": "dddd",
"plan": [{
"lat": "13.1234",
"long": "7.1234",
"imagepath": "sd / image / demo.jpg"
},{
"lat": "13.1234",
"long": "7.1234",
"imagepath": "sd / image / demo.jpg"
}]
}
JSON OBJECT when their is only one plan.
{
"ocrNumber": "0123456",
"userName": "dddd",
"plan": {
"lat": "13.1234",
"long": "7.1234",
"imagepath": "sd / image / demo.jpg"
}
}
add dependencies in your app level gradle file.
implementation 'com.google.code.gson:gson:2.8.5'
Create MyResponse.java
public class MyResponse {
#SerializedName("ocrNumber")
private String ocrNumber;
#SerializedName("userName")
private String userName;
#SerializedName("plan")
private ArrayList<Plan> plan;
public String getOcrNumber() {
return ocrNumber;
}
public void setOcrNumber(String ocrNumber) {
this.ocrNumber = ocrNumber;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public ArrayList<Plan> getPlan() {
return plan;
}
public void setPlan(ArrayList<Plan> plan) {
this.plan = plan;
}
}
create Plan.java class
public class Plan {
#SerializedName("lat")
private String lat;
#SerializedName("long")
private String longStr;
#SerializedName("imagepath")
private String imagepath;
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLongStr() {
return longStr;
}
public void setLongStr(String longStr) {
this.longStr = longStr;
}
public String getImagepath() {
return imagepath;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
}
Convert your jsonString to object using Gson
Gson gson = new Gson();
MyResponse response = gson.fromJson(yourJsonString, MyResponse.class);
Related
Here I want to send a hashMap as a Post request data.
In my Post request I have to send Data like
{
"dd98e151-3a57-45f5-b201-e7f5250bce8b": {
"ratingid": "64d2fa13-bf17-4242-9106-c1a722cd1063",
"compid": "dd98e151-3a57-45f5-b201-e7f5250bce8b",
"avgrat": "4.00",
"continue": " ",
"improve": " ",
"ratingindicators": [
{
"internalname": "c1",
"name": "CI 1",
"rating": "4"
},
{
"internalname": "CI 3",
"name": "CI 3 only ",
"feedback": "text"
},
{
"internalname": "I2",
"name": "CI 2",
"rating": "0"
}
]
},
"e6c6d37c-a9e6-491f-9f76-8375cee2096f": {
"ratingid": "64d2fa13-bf17-4242-9106-c1a722cd1063",
"compid": "dd98e151-3a57-45f5-b201-e7f5250bce8b",
"avgrat": "4.00",
"continue": " ",
"improve": " ",
"ratingindicators": [
{
"internalname": "c1",
"name": "CI 1",
"rating": "4"
},
{
"internalname": "CI 3",
"name": "CI 3 only ",
"feedback": "text"
},
{
"internalname": "I2",
"name": "CI 2",
"rating": "0"
}
]
}
}
To post that data in API call I have created a HashMap like
Map<String,PostIndicatorsModel>> map=new HashMap<String,PostIndicatorsModel>();
And Here PostIndicatorsModel is an pojo/model class
PostIndicatorsModel.java
public class FeeddbackPostIndicatorsModel {
#SerializedName("ratingid")
#Expose
private String feedbackratingid;
#SerializedName("compid")
#Expose
private String competencyid;
#SerializedName("avgrat")
#Expose
private String avgrating;
#SerializedName("continue")
#Expose
private String whattocontinue = "";
#SerializedName("improve")
#Expose
private String whattoimprove = "";
#SerializedName("ratingindicators")
#Expose
private List<Ratingindicator> ratingindicators = null;
public String getRatingid() {
return ratingid;
}
public void setRatingid(String ratingid) {
this.ratingid = ratingid;
}
public String getCompid() {
return compid;
}
public void setCompid(String compid) {
this.compid = compid;
}
public String getAvgrat() {
return avgrat;
}
public void setAvgrat(String avgrat) {
this.avgrat = avgrat;
}
public String getContinue() {
return _continue;
}
public void setContinue(String _continue) {
this._continue = _continue;
}
public String getImprove() {
return improve;
}
public void setImprove(String improve) {
this.improve = improve;
}
public List<Ratingindicator> getRatingindicators() {
return ratingindicators;
}
public void setRatingindicators(List<Ratingindicator> ratingindicators) {
this.ratingindicators = ratingindicators;
}
public static class Ratingindicator{
#SerializedName("internalname")
#Expose
private String internalname;
#SerializedName("name")
#Expose
private String name;
#SerializedName("rating")
#Expose
private String rating;
#SerializedName("feedback")
#Expose
private String feedback;
public String getInternalname() {
return internalname;
}
public void setInternalname(String internalname) {
this.internalname = internalname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getFeedback() {
return feedback;
}
public void setFeedback(String feedback) {
this.feedback = feedback;
}
}
}
Please help me to understand how to call post API with this HashMap
Map<String,PostIndicatorsModel>> map=new HashMap<String,PostIndicatorsModel>();
In API call
#FormUrlEncoded
#POST(SURL.POST_INDICATORS)
Call<PostIndicatorsModel> postRate360(#Path("rateId") String rateId, #Body Map<String,PostIndicatorsModel> post);
I tried with #Body, #FeildMap,#QueryMap but it shows an error in call or server not getting data from post-call as required.
Please help me to understand how can i do this
I'm having some difficulty in parsing a response from a RestTemplate into an instance of a class I've defined.
When I come to process the results, it does give me the correct number of items in the array, but they are all set to default values - it seems unable to process the actual contents from each entry in the response.
This is my class:
public class Authority {
private long localAuthorityId;
private String localAuthorityIdCode;
private String name;
private String friendlyName;
private String url;
private String schemeUrl;
private String email;
private String regionName;
private String fileName;
private String fileNameWelsh;
private int establishmentCount;
private String creationDate;
private String lastPublishedDate;
private int schemeType;
private Link[] links;
public Authority() {}
public Authority (long localAuthorityId, String localAuthorityIdCode, String name, String friendlyName, String url, String schemeUrl,
String email, String regionName, String fileName, String fileNameWelsh, int establishmentCount, String creationDate,
String lastPublishedDate, int schemeType, Link[] links) {
this.localAuthorityId = localAuthorityId;
this.localAuthorityIdCode = localAuthorityIdCode;
this.name = name;
this.friendlyName = friendlyName;
this.url = url;
this.schemeUrl = schemeUrl;
this.email = email;
this.regionName = regionName;
this.fileName = fileName;
this.fileNameWelsh = fileNameWelsh;
this.establishmentCount = establishmentCount;
this.creationDate = creationDate;
this.lastPublishedDate = lastPublishedDate;
this.schemeType = schemeType;
this.links = links;
}
public long getLocalAuthorityId() {
return this.localAuthorityId;
}
public String getLocalAuthorityIdCode() {
return this.localAuthorityIdCode;
}
public String getName() {
return this.name;
}
public String getFriendlyName() {
return this.friendlyName;
}
public String getUrl() {
return this.url;
}
public String getSchemeUrl() {
return this.schemeUrl;
}
public String getEmail() {
return this.email;
}
public String getRegionName() {
return this.regionName;
}
public String getFilename() {
return this.fileName;
}
public String getFileNameWelsh() {
return this.fileNameWelsh;
}
public int getEstablishmentCount() {
return this.establishmentCount;
}
public String getCreationDate() {
return this.creationDate;
}
public String getLastPublishedDate() {
return this.lastPublishedDate;
}
public int getSchemeType() {
return this.schemeType;
}
public Link[] getLinks() {
return this.links;
}
}
This is my response wrapper (where I've confirmed it only ever calls the empty constructor):
public class MyResponseWrapper {
private Authority[] authorities;
public MyResponseWrapper() {
// this is always being called
}
public MyResponseWrapper(Authority[] authorities) {
this.authorities = authorities;
}
public Authority[] getAuthorities() {
return this.authorities;
}
}
And this is how I'm using the RestTemplate:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity<MyResponseWrapper> res = restTemplate.exchange(url, HttpMethod.GET, entity, MyResponseWrapper.class);
Here is the JSON I am attempting to parse (I only need the id and name parameters to be stored in MyClass):
{
"authorities":[
{
"LocalAuthorityId":197,
"LocalAuthorityIdCode":"760",
"Name":"Aberdeen City",
"FriendlyName":"aberdeen-city",
"Url":"http://www.aberdeencity.gov.uk",
"SchemeUrl":"",
"Email":"commercial#aberdeencity.gov.uk",
"RegionName":"Scotland",
"FileName":"http://ratings.food.gov.uk/OpenDataFiles/FHRS760en-GB.xml",
"FileNameWelsh":null,
"EstablishmentCount":1847,
"CreationDate":"2010-08-17T15:30:24.87",
"LastPublishedDate":"2018-02-08T00:35:50.717",
"SchemeType":2,
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities/197"
}
]
},
{
"LocalAuthorityId":198,
"LocalAuthorityIdCode":"761",
"Name":"Aberdeenshire",
"FriendlyName":"aberdeenshire",
"Url":"http://www.aberdeenshire.gov.uk/",
"SchemeUrl":"",
"Email":"environmental#aberdeenshire.gov.uk",
"RegionName":"Scotland",
"FileName":"http://ratings.food.gov.uk/OpenDataFiles/FHRS761en-GB.xml",
"FileNameWelsh":null,
"EstablishmentCount":2102,
"CreationDate":"2010-08-17T15:30:24.87",
"LastPublishedDate":"2018-02-24T00:34:15.547",
"SchemeType":2,
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities/198"
}
]
},
{
"LocalAuthorityId":277,
"LocalAuthorityIdCode":"323",
"Name":"Adur",
"FriendlyName":"adur",
"Url":"http://www.adur-worthing.gov.uk",
"SchemeUrl":"",
"Email":"publichealth.regulation#adur-worthing.gov.uk",
"RegionName":"South East",
"FileName":"http://ratings.food.gov.uk/OpenDataFiles/FHRS323en-GB.xml",
"FileNameWelsh":null,
"EstablishmentCount":417,
"CreationDate":"2010-08-17T15:30:24.87",
"LastPublishedDate":"2018-02-28T00:36:33.987",
"SchemeType":1,
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities/277"
}
]
},
{
"LocalAuthorityId":158,
"LocalAuthorityIdCode":"055",
"Name":"Allerdale",
"FriendlyName":"allerdale",
"Url":"http://www.allerdale.gov.uk",
"SchemeUrl":"",
"Email":"environmental.health#allerdale.gov.uk",
"RegionName":"North West",
"FileName":"http://ratings.food.gov.uk/OpenDataFiles/FHRS055en-GB.xml",
"FileNameWelsh":null,
"EstablishmentCount":1092,
"CreationDate":"2010-08-17T15:30:24.87",
"LastPublishedDate":"2018-02-28T00:33:58.31",
"SchemeType":1,
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities/158"
}
]
},
{
"LocalAuthorityId":48,
"LocalAuthorityIdCode":"062",
"Name":"Amber Valley",
"FriendlyName":"amber-valley",
"Url":"http://www.ambervalley.gov.uk",
"SchemeUrl":"",
"Email":"envhealth#ambervalley.gov.uk",
"RegionName":"East Midlands",
"FileName":"http://ratings.food.gov.uk/OpenDataFiles/FHRS062en-GB.xml",
"FileNameWelsh":null,
"EstablishmentCount":972,
"CreationDate":"2010-08-17T15:30:24.87",
"LastPublishedDate":"2018-02-28T00:34:14.493",
"SchemeType":1,
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities/48"
}
]
},
{
"LocalAuthorityId":334,
"LocalAuthorityIdCode":"551",
"Name":"Anglesey",
"FriendlyName":"anglesey",
"Url":"http://www.ynysmon.gov.uk",
"SchemeUrl":"",
"Email":"iechydyramgylchedd#ynysmon.gov.uk",
"RegionName":"Wales",
"FileName":"http://ratings.food.gov.uk/OpenDataFiles/FHRS551en-GB.xml",
"FileNameWelsh":"http://ratings.food.gov.uk/OpenDataFiles/FHRS551cy-GB.xml",
"EstablishmentCount":703,
"CreationDate":"2010-08-17T15:30:24.87",
"LastPublishedDate":"2018-02-28T00:34:28.853",
"SchemeType":1,
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities/334"
}
]
}
],
"meta":{
"dataSource":"API",
"extractDate":"2018-02-28T00:58:26.2673908+00:00",
"itemCount":6,
"returncode":"OK",
"totalCount":6,
"totalPages":1,
"pageSize":6,
"pageNumber":1
},
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities"
},
{
"rel":"first",
"href":"http://api.ratings.food.gov.uk/authorities/1/6"
},
{
"rel":"previous",
"href":"http://api.ratings.food.gov.uk/authorities/1/6"
},
{
"rel":"next",
"href":"http://api.ratings.food.gov.uk/authorities/1/6"
},
{
"rel":"last",
"href":"http://api.ratings.food.gov.uk/authorities/1/6"
}
]
}
I know I'm making a really basic mistake in attempting to parse this response. Would really appreciate if someone could point it out. Cheers.
I have JSON like this
{
"data":
[
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
}
]
}
]
}
I am using JSON Object to de-Serialize the data
this is what i am trying to
JSONObject jsonObj = new JSONObject(jsonStr);
String first = jsonObj.getJSONObject("data").getString("name");
System.out.println(first);
But a Cant seem to get the name or anything
Not sure what i am doing wrong?
and then i am trying to display it into a listview but haven't got to that part yet
data is a JSON Array, not a JSONObject
try: jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
also note the difference between getString and optString, if you don't want an exception on null use the later.
First parse your Json from below method,
private ArrayList<String> getStringFromJson(String jsonStr)
{
ArrayList<String> mNames = new ArrayList<String>();
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
mNames= row.getString("Name");
}
return mNames;
}
try {
JSONObject jsonObj = new JSONObject(jsonStr);
jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
} catch (JSONException e) {
}
Data is a json array. Use getJsonObject for json objects.
Refer to this example to create a ListView and populate it's adapter with data from a json object.
Use GSON instead JSON. Hope it helps you.
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
List<Data> datas= new ArrayList<Data>();
datas= Arrays.asList(gson.fromJson(jsonString, Data[].class));
public class Ingredients {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
public class Data {
private int id;
private String Name;
private String Image;
private String Category;
private String Method;
public List<Ingredients> getIngredients() {
return Ingredients;
}
public void setIngredients(List<Ingredients> ingredients) {
Ingredients = ingredients;
}
private List<Ingredients> Ingredients = new ArrayList<Ingredients>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
}
My JSON response has the following structure.
How should i parse it to store in a list in java with the structure maintained.
Does GSON provide a solution or should i use multidimensional array list?
I need to pass each of the tag array to a different view pager what approach should I follow.
{
"tag": [
{
"listing_count": 5,
"listings": [
{
"source": "source1",
"data": {
"image": "image1",
"name": "name1"
},
"name": "name1"
}
]
},
{
"listing_count": 5,
"listings": [
{
"source": "source2",
"data": {
"image": "imag2",
"name": "name2"
},
"name": "name2"
}
]
}
]
}
EDIT:
I have created the classes as suggested in the answer..I am having trouble creating the GSON response class.
This is what I have created:
public GsonRequest(int method, String url, Class<T> clazz,
Listener<T> listener, ErrorListener errorListener, Gson gson) {
super(Method.GET, url, errorListener);
this.mClazz = clazz;
this.mListener = listener;
mGson = gson;
}
The gson class should be something like this:
public class TagList {
ArrayList<Tag> tags;
public static class Tag {
int listing_count;
ArrayList<Listings> listings;
public int getListing_count() {
return listing_count;
}
public void setListing_count(int listing_count) {
this.listing_count = listing_count;
}
public ArrayList<Listings> getListings() {
return listings;
}
public void setListings(ArrayList<Listings> listings) {
this.listings = listings;
}
}
public static class Listings {
String source;
Data data;
String name;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class Data {
String image;
String name;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I am creating this json string from the server as shown below and I was able to parse the string too. But when creating the json some fields like errormessage,createdDate,priority are null values. I dont want to show them in the string how can I do that?
Json Strin
{
"errormessage": null,
"createdDate": null,
"list": [{
"type": "app1",
"alternateId": "AlternateID",
"priority": null,
"description": "app for desc",
}],
"locationName": null,
"facilityManagerName": null,
"codeName": null,
"sourceKey": null,
"tablename": null,
"path": "list",
"service": "listserver",
"license": null,
"key": null,
}
expected String
{
"list": [{
"type": "app1",
"alternateId": "AlternateID",
"description": "app for desc",
}],
"path": "list",
"service": "listserver",
}
Generic Java Bean For creating the json:
public class AppObject<T> implements Serializable {
private String errormessage;
private Date createdDate;
private List<T> list;
private String locationName;
private String facilityManagerName;
private String codeName;
private Long sourceKey;
private String tablename;
private String path;
private String service;
private String license;
private Long key;
public AppObject() {
list = new ArrayList<T>();
}
public AppObject(List<T> list) {
this.list = list;
}
#XmlAnyElement(lax = true)
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getTablename() {
return tablename;
}
public void setTablename(String tablename) {
this.tablename = tablename;
}
public String getErrormessage() {
return errormessage;
}
public void setErrormessage(String errormessage) {
this.errormessage = errormessage;
}
public Long getKey() {
return key;
}
public void setKey(Long key) {
this.key = key;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getFacilityManagerName() {
return facilityManagerName;
}
public void setFacilityManagerName(String facilityManagerName) {
this.facilityManagerName = facilityManagerName;
}
public Date getCreatedFeedFromDate() {
return createdFeedFromDate;
}
#JsonDeserialize(using = com.vxl.JsonDateDeserializer.class)
public void setCreatedFeedFromDate(Date createdFeedFromDate) {
this.createdFeedFromDate = createdFeedFromDate;
}
public Date getCreatedDate() {
return createdFeedToDate;
}
#JsonDeserialize(using = com.vxl.JsonDateDeserializer.class)
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
Honestly, I really wouldn't spend time on making a payload "look nice". Now if you said that you were motivated to keep the payload small for efficiency reasons I'd buy that.
Perhaps you use Jackson for serialising to JSON as well (I don't see why you are using two different libraries). I think that this question shows that Jackson's treatment of nulls can be controlled.
Change your get method. Set if(something!=null)return something; instead of return something;