Parsing of multiple Arrays in android - java

Please tell me how i can parse this model, i am a fresher in android. i tried like this way:-
{ "error": false, "response": { "comdata": [{ "id": "35", "address": "Address" }], "empdata": [{ "cid": "33", "comid": "35", "empname": "test", "empdob": "0000-00-00" }, { "cid": "33", "comid": "35", "empname": "test", "empdob": "0000-00-00" }] }
Gson gson = new Gson();
String json = gson.toJson(result);
JSONObject jObj = new JSONObject(json);
if (jObj.getString("error").equalsIgnoreCase("false")) {
JSONObject object = jObj.getJSONObject("response");
for (int i = 0; i < object.length(); i++) {
JSONArray jsonArray = object.getJSONArray("parentdata");
JSONObject jsonObject = jsonArray.getJSONObject(0);
//Something write here
JSONArray jsonArray1 = object.getJSONArray("childata");
for (int a = 0; a < jsonArray1.length(); a++) {
JSONObject object1 = jsonArray1.getJSONObject(a);
} return "true";
}return "true";
}else{
}

Your JSON is invalid correct JSON will look like this.
{
"error": false,
"response": {
"comdata": [
{
"id": "35",
"address": "Address"
}
],
"empdata": [
{
"cid": "33",
"comid": "35",
"empname": "test",
"empdob": "0000-00-00"
},
{
"cid": "33",
"comid": "35",
"empname": "test",
"empdob": "0000-00-00"
}
]
}
}
You can parse the JSON using below code.
private void parseResponse(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.getBoolean("error")) {
JSONObject response = jsonObject.getJSONObject("response");
JSONArray jsonArray1 = response.getJSONArray("comdata");
List<ComData> comdataList = new ArrayList<>();
for (int i = 0; i < jsonArray1.length(); i++) {
ComData comData = new ComData();
comData.setId(jsonArray1.getJSONObject(i).getString("id"));
comData.setAddress(jsonArray1.getJSONObject(i).getString("address"));
comdataList.add(comData);
}
JSONArray jsonArray2 = response.getJSONArray("empdata");
List<EmpData> empdataList = new ArrayList<>();
for (int i = 0; i < jsonArray2.length(); i++) {
EmpData empData = new EmpData();
empData.setCid(jsonArray2.getJSONObject(i).getString("cid"));
empData.setComid(jsonArray2.getJSONObject(i).getString("comid"));
empData.setEmpname(jsonArray2.getJSONObject(i).getString("empname"));
empData.setEmpdob(jsonArray2.getJSONObject(i).getString("empdob"));
empdataList.add(empData);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Or you can easily parse JSON to POJO using GSON, refer César Ferreira's answer.

Your JSON is invalid you should have it something like this:
{
"error": false,
"response": {
"comdata": [{
"id": "10",
"username": null,
"email": "example#gmail.com"
}],
"empdata": [{
"eid": "33",
"empname": "test",
"empdob": "0000-00-00",
"empgender": "test",
"empphoto": ""
}],
"someData": [{
"eid": "34",
"empname": "test",
"empdob": "0000-00-00",
"empgender": "test",
"empphoto": ""
}]
}
}
The property someData I had to add it so it would be a valid JSON, I don't know if it fits your requirements.
You can use jsonschematopojo to generate a class like this:
Comdatum class
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Comdatum {
#SerializedName("id")
#Expose
private String id;
#SerializedName("username")
#Expose
private Object username;
#SerializedName("email")
#Expose
private String email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object getUsername() {
return username;
}
public void setUsername(Object username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Data class
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Data {
#SerializedName("error")
#Expose
private Boolean error;
#SerializedName("response")
#Expose
private Response response;
public Boolean getError() {
return error;
}
public void setError(Boolean error) {
this.error = error;
}
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
}
Empdatum Class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import package com.example;
public class Empdatum {
#SerializedName("eid")
#Expose
private String eid;
#SerializedName("empname")
#Expose
private String empname;
#SerializedName("empdob")
#Expose
private String empdob;
#SerializedName("empgender")
#Expose
private String empgender;
#SerializedName("empphoto")
#Expose
private String empphoto;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getEmpdob() {
return empdob;
}
public void setEmpdob(String empdob) {
this.empdob = empdob;
}
public String getEmpgender() {
return empgender;
}
public void setEmpgender(String empgender) {
this.empgender = empgender;
}
public String getEmpphoto() {
return empphoto;
}
public void setEmpphoto(String empphoto) {
this.empphoto = empphoto;
}
}
Response Class
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Response {
#SerializedName("comdata")
#Expose
private List<Comdatum> comdata = null;
#SerializedName("empdata")
#Expose
private List<Empdatum> empdata = null;
#SerializedName("someData")
#Expose
private List<SomeDatum> someData = null;
public List<Comdatum> getComdata() {
return comdata;
}
public void setComdata(List<Comdatum> comdata) {
this.comdata = comdata;
}
public List<Empdatum> getEmpdata() {
return empdata;
}
public void setEmpdata(List<Empdatum> empdata) {
this.empdata = empdata;
}
public List<SomeDatum> getSomeData() {
return someData;
}
public void setSomeData(List<SomeDatum> someData) {
this.someData = someData;
}
}
SomeDatum Class
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class SomeDatum {
#SerializedName("eid")
#Expose
private String eid;
#SerializedName("empname")
#Expose
private String empname;
#SerializedName("empdob")
#Expose
private String empdob;
#SerializedName("empgender")
#Expose
private String empgender;
#SerializedName("empphoto")
#Expose
private String empphoto;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getEmpdob() {
return empdob;
}
public void setEmpdob(String empdob) {
this.empdob = empdob;
}
public String getEmpgender() {
return empgender;
}
public void setEmpgender(String empgender) {
this.empgender = empgender;
}
public String getEmpphoto() {
return empphoto;
}
public void setEmpphoto(String empphoto) {
this.empphoto = empphoto;
}
}
And Then you can just do something like this:
String jsonString = "Your JSON String";
Gson converter = new Gson();
Data settingsdata = converter.fromJson(jsonString , Data.class);

Related

success is false from server

Hi in the below code success is false from server while parsing json data.status code is 200 and created.
Login Modules class contains list of strings and GetModuleList contains a list of strings but in the modules is an array it contains a list of objects
LoginModules.java:
public class LoginModules {
#SerializedName("success")
private String success;
#SerializedName("result")
private List<GetLoginModuleList> result;
public List<GetLoginModuleList> getResult() {
return result;
}
public void setResult(List<GetLoginModuleList> result) {
this.result = result;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
GetLoginModuleList.java:
public class GetLoginModuleList {
#SerializedName("session")
#Expose
private String session;
#SerializedName("userid")
#Expose
private String userid;
#SerializedName("vtiger_version")
#Expose
private String vtiger_version;
#SerializedName("modules")
#Expose
private List<Modules> modules;
public List<Modules> getModules() {
return modules;
}
public void setModules(List<Modules> modules) {
this.modules = modules;
}
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getVtiger_version() {
return vtiger_version;
}
public void setVtiger_version(String vtiger_version) {
this.vtiger_version = vtiger_version;
}
public String getMobile_module_version() {
return mobile_module_version;
}
public void setMobile_module_version(String mobile_module_version) {
this.mobile_module_version = mobile_module_version;
}
#SerializedName("mobile_module_version")
#Expose
private String mobile_module_version;
}
GetLoginModulesList.java:
public class GetLoginModuleList {
#SerializedName("login")
private GetLoginList login;
public GetLoginList getLogin() {
return login;
}
public void setLogin(GetLoginList login) {
this.login = login;
}
public List<Modules> getModules() {
return modules;
}
public void setModules(List<Modules> modules) {
this.modules = modules;
}
#SerializedName("modules")
private List<Modules> modules;
}
Modules.java:
public class Modules {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("isEntity")
#Expose
private String isEntity;
#SerializedName("label")
#Expose
private String label;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsEntity() {
return isEntity;
}
public void setIsEntity(String isEntity) {
this.isEntity = isEntity;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSingular() {
return singular;
}
public void setSingular(String singular) {
this.singular = singular;
}
#SerializedName("singular")
#Expose
private String singular;
}
Json response:
{
"success": true,
"result": {
"login": {
"userid": "1",
"session": "fa000f0a6c5a414e62dcc4cbf99175d6",
"vtiger_version": "5.2.0",
"mobile_module_version": "1.2.1"
},
"modules": [
{
"id": "1",
"name": "Calendar",
"isEntity": true,
"label": "Calendar",
"singular": "To Do"
},
{
"id": "2",
"name": "Leads",
"isEntity": true,
"label": "Leads",
"singular": "Lead"
},
]
}
}
Activity.java:
if (response.isSuccessful()) {
LoginModules loginModules = response.body();
String success = loginModules.getSuccess()
.toString();
if (success.equals("true")) {
String result = loginModules.getResult()
.toString();
Log.i("result", ":" + result);
String Userid = loginModules.getResult()
.getUserid();
Log.i("Userid", ":" + Userid);
String Session = loginModules.getResult()
.getSession();
Log.i("Session", ":" + Session);
String Vtiger_version = loginModules.getResult()
.getVtiger_version();
Log.i("Vtiger_version", ":" + Vtiger_version);
String Mobile_module_version = loginModules.getResult()
.getMobile_module_version();
Log.i("Mobile_module_version", ":" + Mobile_module_version);
//List<Modules> modules = new ArrayList<>();
//Gson gson = new Gson();
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray("modules");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = null;
try {
jsonobject = jsonarray.getJSONObject(i);
String id = jsonobject.getString("id");
Log.i("id", ":" + id);
// String url = jsonobject.getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
}
if (username.equals("admin") && pass.equals("Password!1")) {
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG)
.show();
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
finish();
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG)
.show();
}
}
}
Some data is missing in your model structure for parsing data.
"result": {
"login": {
"userid": "1",
"session": "fa000f0a6c5a414e62dcc4cbf99175d6",
"vtiger_version": "5.2.0",
"mobile_module_version": "1.2.1"
},
there is a "login" jsonobject in your "result" object. But you missed the "login" element when you parse it. you should create a java class as LoginModel.
public class LoginModel {
#SerializedName("session")
#Expose
private String session;
#SerializedName("userid")
#Expose
private String userid;
#SerializedName("vtiger_version")
#Expose
private String vtiger_version;
and put login model in your GetModuleList class.
public class GetLoginModuleList {
#SerializedName("login")
#Expose
private LoginModel login;

Gson - Parse from Json to a typed ArrayList<T>

Generated GSON JAVA classes from JSON Response. I am trying to parse the Address1 and Address from the Address_.java class. It was generated from the JSON response. I am using GSON to parse it and and trying read the value of Address1 and Address2 from it. I tried different ways to parse but attempt was not successful.
AddressList.java
public class AddressList {
#SerializedName("_embedded")
#Expose
private Embedded embedded;
public Embedded getEmbedded() {
return embedded;
}
public void setEmbedded(Embedded embedded) {
this.embedded = embedded;
}
}
Embedded.java
public class Embedded {
#SerializedName("address")
#Expose
private List<Address> address = null;
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
}
Address.java
public class Address {
#SerializedName("_links")
#Expose
private Links_ links;
#SerializedName("_embedded")
#Expose
private Object embedded;
#SerializedName("customer")
#Expose
private String customer;
#SerializedName("account")
#Expose
private String account;
#SerializedName("address1")
#Expose
private String address1;
#SerializedName("address2")
#Expose
private String address2;
public Links_ getLinks() {
return links;
}
public void setLinks(Links_ links) {
this.links = links;
}
public Object getEmbedded() {
return embedded;
}
public void setEmbedded(Object embedded) {
this.embedded = embedded;
}
public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
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;
}
}
GSON RESPONSE
{
"_links": {
"self": {
"href": "https://xxxxx/xxx/address?where=xxx%20eq%20xx%20and%20customer%20eq%xxxx&page=1&pagesize=50"
}
},
"_embedded": {
"address": [
{
"_links": {
"self": {
"href": "https://xxxx/xxxx/xxxx/xxxx"
}
},
"_embedded": null,
"customer": "12345",
"account": "",
"address1": "111 ABC DR",
"address2": " ",
}
]
},
"totalItems": 1,
"pageSize": 50,
"totalPages": 1,
"currentPage": 1
}
Can someone please help me? Thanks
Thanks GhostCat. I removed the _embedded from the response and the object itself and it started working. It was third party webservices was sending the response with _. It's working now.

How to convert Json into a Java bean object?

I am trying to convert a complex object into related Java beans. However, some sub class can be not generated correctly.
I am just using simulate MS Adaptive card to create a set of Java beans classes. When I call Gson package or Alibaba fastJson package to parse my json data. it always shows the super class type.
This is just an experiment to test Gson & fastJson whether it can convert complex objects. which is running on the Android studio.
My demo json is like following:
{
"type": "AdaptiveCard",
"version": "1.0",
"id": "workloadQCactivity 20",
"speak": "activity 20 <break time=\"300ms\"/> at<break time=\"300ms\"/> <break time=\"300ms\"/>building<break time=\"300ms\"/>A<break time=\"300ms\"/>floor<break time=\"300ms\"/>1<break time=\"300ms\"/>room<break time=\"300ms\"/>1<break time=\"300ms\"/> ",
"body": [{
"type": "Container",
"items": [{
"type": "ColumnSet",
"columns": [{
"type": "Column",
"width": "Stretch",
"items": [{
"type": "TextBlock",
"size": "large",
"weight": "bolder",
"text": "activity 20 at building A floor 1 room 1",
"wrap": true
}]
}]
}]
}],
"actions": [{
"type": "Action.ShowCard",
"card": {
"type": "AdaptiveCard",
"version": "1.0",
"body": [{
"type": "TextBlock",
"size": "medium",
"weight": "bolder",
"isSubtle": true,
"text": "have thing to check list1",
"wrap": true
}, {
"type": "TextBlock",
"weight": "bolder",
"isSubtle": true,
"text": "this is section 1",
"wrap": true
}, {
"type": "TextBlock",
"isSubtle": true,
"text": "q1 of s1",
"wrap": true
}, {
"type": "TextBlock",
"isSubtle": true,
"text": "q2 of s2",
"wrap": true
}, {
"type": "TextBlock",
"weight": "bolder",
"isSubtle": true,
"text": "this is section 2",
"wrap": true
}, {
"type": "TextBlock",
"isSubtle": true,
"text": "q1 of s22",
"wrap": true
}, {
"type": "TextBlock",
"size": "medium",
"weight": "bolder",
"isSubtle": true,
"text": "have checklist 2",
"wrap": true
}, {
"type": "TextBlock",
"weight": "bolder",
"isSubtle": true,
"text": "section of the second checklist",
"wrap": true
}, {
"type": "TextBlock",
"isSubtle": true,
"text": "qqqqqq",
"wrap": true
}]
},
"title": "Show Checklist"
}]
}
Therefore, I just follow MS adaptive card to create following java beans.
First class: AdaptiveTypedElement
public class AdaptiveTypedElement {
#JsonProperty("additionalPorperties")
public Map<String, Object> additionalPorperties = new HashMap<String, Object>();
//#JsonProperty("type")
//public String type;
#JsonProperty("id")
public String id;
}
Second class: AdaptiveTypedElement
public class AdaptiveElement extends AdaptiveTypedElement {
#JsonProperty("spacing")
public AdaptiveSpacing spacing ;
#JsonProperty("separator")
public boolean separator = false;
#JsonProperty("speak")
public String speak;
#JsonProperty("separation")
// public AdaptiveSeparationStyle separation;
public String separation;
}
Third class AdaptiveContainer:
public class AdaptiveContainer extends AdaptiveElement {
#JsonProperty("typeName")
public String typeName = "Container";
#JsonProperty("type")
public String type = "Container";
#JsonProperty("items")
public List<AdaptiveElement> items = new ArrayList<AdaptiveElement>();
#JsonProperty("selectAction")
public AdaptiveAction selectAction = null;
#JsonProperty("style")
public AdaptiveContainerStyle style = AdaptiveContainerStyle.Default;
}
public class AdaptiveColumnSet extends AdaptiveElement {
#JsonProperty("typeName")
public final String typeName = "ColumnSet";
#JsonProperty("type")
public final String type = "ColumnSet";
#JsonProperty("columns")
public List<AdaptiveColumn> columns = new ArrayList<AdaptiveColumn>();
#JsonProperty("selectionAction")
public AdaptiveAction selectionAction = null;
}
public class AdaptiveColumn extends AdaptiveContainer{
#JsonProperty("typeName")
public final String typeName = "Column";
#JsonProperty("type")
public final String type = "Column";
#JsonProperty("size")
public String size;
#JsonProperty("with")
public String with;
}
public class AdaptiveAction {
#JsonProperty("title")
public String title;
#JsonProperty("speak")
public String speak;
}
public class AdaptiveShowCardAction extends AdaptiveAction {
#JsonProperty("typeName")
public final String typeName = "Action.ShowCard";
#JsonProperty("type")
public final String Type = "Action.ShowCard";
#JsonProperty("card")
public AdaptiveCard card;
}
public class AdaptiveTextBlock extends AdaptiveElement{
#JsonProperty("typeName")
public String typeName = "TextBlock";
#JsonProperty("type")
public String type = "TextBlock";
#JsonProperty("text")
public String text = "";
#JsonProperty("size")
public AdaptiveTextSize size;
#JsonProperty("weight")
public AdaptiveTextWeight weight;
#JsonProperty("color")
public AdaptiveTextColor color;
#JsonProperty("horizontalAlignment")
public AdaptiveHorizontalAlignment horizontalAlignment = AdaptiveHorizontalAlignment.Left;
#JsonProperty("wrap")
public boolean wrap = false;
#JsonProperty("isSubtle")
public boolean isSubtle = false;
#JsonProperty("maxLines")
public int maxLines = 0;
#JsonProperty("maxWidth")
public int maxWidth = 0;
}
public class AdaptiveCard extends AdaptiveTypedElement {
#JsonProperty("contentType")
public final String contentType = "application/vnd.microsoft.card.adaptive";
#JsonProperty("typeName")
public final String typeName = "AdaptiveCard";
#JsonProperty("type")
public String type = "AdaptiveCard";
#JsonProperty("body")
public List<AdaptiveElement> body = new ArrayList<AdaptiveElement>();
#JsonProperty("actions")
public List<AdaptiveAction> actions = new ArrayList<AdaptiveAction>();
#JsonProperty("speak")
public String speak = null;
#JsonProperty("title")
public String title;
#JsonProperty("version")
//public AdaptiveSchemaVersion version = null;
public String version = null;
#JsonProperty("fallbackText")
public String fallbackText = null;
#JsonProperty("lang")
public String lang = null;
}
In the end, I finally got AdaptiveCard Object. See my code:
return JSON.parseObject(attachJson, AdaptiveCard.class). Note that I add "implementation 'com.alibaba:fastjson:1.2.54'" in my Android Studio
When I check this object, I found the Body data member should be class "AdaptiveContainer " not "AdaptiveElement". I was wondering why it did not following subclass mechanism of OOP & OOD. I am expecting "AdaptiveContainer", but actually output is "AdaptiveElement".
enter image description here
rib-pet, your question has a far to big example. Anyway I tried to create a java class mapping for your sample using GSON
Action.java
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Action {
#SerializedName("type")
#Expose
private String type;
#SerializedName("card")
#Expose
private Card card;
#SerializedName("title")
#Expose
private String title;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Body.java
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Body {
#SerializedName("type")
#Expose
private String type;
#SerializedName("items")
#Expose
private List<Item> items = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
Body_.java (dependend on your wished model you should integrate this class better in some existing
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Body_ {
#SerializedName("type")
#Expose
private String type;
#SerializedName("size")
#Expose
private String size;
#SerializedName("weight")
#Expose
private String weight;
#SerializedName("isSubtle")
#Expose
private Boolean isSubtle;
#SerializedName("text")
#Expose
private String text;
#SerializedName("wrap")
#Expose
private Boolean wrap;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public Boolean getIsSubtle() {
return isSubtle;
}
public void setIsSubtle(Boolean isSubtle) {
this.isSubtle = isSubtle;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Boolean getWrap() {
return wrap;
}
public void setWrap(Boolean wrap) {
this.wrap = wrap;
}
}
Card.java
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Card {
#SerializedName("type")
#Expose
private String type;
#SerializedName("version")
#Expose
private String version;
#SerializedName("body")
#Expose
private List<Body_> body = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public List<Body_> getBody() {
return body;
}
public void setBody(List<Body_> body) {
this.body = body;
}
}
Column.java
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Column {
#SerializedName("type")
#Expose
private String type;
#SerializedName("width")
#Expose
private String width;
#SerializedName("items")
#Expose
private List<Item_> items = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public List<Item_> getItems() {
return items;
}
public void setItems(List<Item_> items) {
this.items = items;
}
}
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("type")
#Expose
private String type;
#SerializedName("version")
#Expose
private String version;
#SerializedName("id")
#Expose
private String id;
#SerializedName("speak")
#Expose
private String speak;
#SerializedName("body")
#Expose
private List<Body> body = null;
#SerializedName("actions")
#Expose
private List<Action> actions = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSpeak() {
return speak;
}
public void setSpeak(String speak) {
this.speak = speak;
}
public List<Body> getBody() {
return body;
}
public void setBody(List<Body> body) {
this.body = body;
}
public List<Action> getActions() {
return actions;
}
public void setActions(List<Action> actions) {
this.actions = actions;
}
}
Item.java
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Item {
#SerializedName("type")
#Expose
private String type;
#SerializedName("columns")
#Expose
private List<Column> columns = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Column> getColumns() {
return columns;
}
public void setColumns(List<Column> columns) {
this.columns = columns;
}
}
Item_.java also here better integration needed
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Item_ {
#SerializedName("type")
#Expose
private String type;
#SerializedName("size")
#Expose
private String size;
#SerializedName("weight")
#Expose
private String weight;
#SerializedName("text")
#Expose
private String text;
#SerializedName("wrap")
#Expose
private Boolean wrap;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Boolean getWrap() {
return wrap;
}
public void setWrap(Boolean wrap) {
this.wrap = wrap;
}
}
hope it helps!
I've figured out this solution via the following solution:
JSONObject and JSONArray
JSONArray body = contentObj.getJSONArray("body");
JSONArray actions = contentObj.getJSONArray("actions");
title.setText(body.getJSONObject(0).getString("text"));

Map multi-level json string into class object in java

I have following JSON structure:
{
"result": {
"category": [{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": [{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": [{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": []
}]
}]
},
{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": []
}
]
}
}
I need to create class with the above JSON.
I have created two classes as HomeCategoryModel and HomeSubCategoryModel.
There may be multiple sub-categories in each level.
How to map this type of json into classes.
HomeCategoryModel class:
public class HomeCategoryModel {
public int Id;
public String Name;
public String Slug;
public String ImageUrl;
public ArrayList<HomeSubCategoryModel> SubCategories;
//...
//getter, setter
}
HomeSubCategory class:
public class HomeSubCategoryModel {
public int Id;
public String Name;
public String Slug;
public String ImageUrl;
public ArrayList<HomeSubCategoryModel> SubCategories;
//getter setter
}
I have tried to parse using recursive function like this but doesn't seem to work:
JSONObject allLists = jsonObject.getJSONObject("result");
JSONArray catArray = allLists.getJSONArray("category");
ArrayList<HomeCategoryModel> categoryList = new ArrayList<HomeCategoryModel>();
for (int i = 0; i < catArray.length(); i++) {
JSONObject jObj = catArray.getJSONObject(i);
HomeCategoryModel categoryModel = new HomeCategoryModel();
categoryModel.setId(Integer.parseInt(jObj.getString("id")));
categoryModel.setName(jObj.getString("name"));
categoryModel.setSlug(jObj.getString("slug"));
categoryModel.setImageUrl(jObj.getString("image"));
JSONArray productsArray = jObj.getJSONArray("sub-categories");
if (productsArray.length() > 0) {
parseSubCategories(productsArray);
}
categoryList.add(categoryModel);
}
And:
public static ArrayList<HomeSubCategoryModel> parseSubCategories(JSONArray arr) {
ArrayList<HomeSubCategoryModel> subLists = new ArrayList<HomeSubCategoryModel>();
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject childObj = arr.getJSONObject(i);
HomeSubCategoryModel categoryModel = new HomeSubCategoryModel();
categoryModel.setId(Integer.parseInt(childObj.getString("id")));
categoryModel.setName(childObj.getString("name"));
categoryModel.setSlug(childObj.getString("slug"));
categoryModel.setImageUrl(childObj.getString("image"));
JSONArray subArray = childObj.getJSONArray("sub-categories");
if (subArray.length() > 0) {
parseSubCategories(subArray);
}
subLists.add(categoryModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
return subLists;
}
Please suggest me. Thank you.
if you would like to use Gson then i can suggest something like below.
Generate your POJO like this
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public class Result {
#SerializedName("category")
#Expose
private List < Category > category = null;
public List < Category > getCategory() {
return category;
}
public void setCategory(List < Category > category) {
this.category = category;
}
}
public class Category {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("image")
#Expose
private String image;
#SerializedName("sub-categories")
#Expose
private List < SubCategory > subCategories = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List < SubCategory > getSubCategories() {
return subCategories;
}
public void setSubCategories(List < SubCategory > subCategories) {
this.subCategories = subCategories;
}
}
public class SubCategory_ {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("image")
#Expose
private String image;
#SerializedName("sub-categories")
#Expose
private List < Object > subCategories = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List < Object > getSubCategories() {
return subCategories;
}
public void setSubCategories(List < Object > subCategories) {
this.subCategories = subCategories;
}
}
}
and then
Gson gson = new Gson();
Example exp = gson.fromJson("your json string",Example.class);
And you are done.

How to deserialize a JSON Object in a multidimensional array

I have this JSON data and I would like to deserialize it with Android to get it as an object to use in my class.
I get this folowing error :
Could not read JSON: Unrecognized field "card_details"
[
{
"id": "9",
"cat_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"app_id": "null",
"status": "1",
"lft": "1",
"rgt": "2",
"parent_cat_id": "0",
"added_date": "2017-01-12 12:41:29",
"last_edit_date": "2017-01-12 12:46:09",
"language_id": "0",
"category_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"name": "Sport",
"description": "This is sport category",
"image": "notitia/USR-70903638005256656/app-content/cat-img-da1161af03df255a989f8df5fc2e15bd.png",
"tags": "",
"custom_url": "sport",
"card_details": {
"nom_carte": "Pinacolada",
"prix": "5000",
"image": "notitia/USR-44043694343417880/app-content/e0fa7beb401e8fe77727f5a8241ff872.jpg",
"validity": "1"
}
}
]
Here is my AsyncTask to retrieve the data:
private class HttpRequestTaskCarte extends AsyncTask<Void,Void,Item[]> {
#Override
protected Item[] doInBackground(Void... params) {
try {
final String url = "http://domain.com/link.php?target=multi";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Item[] greeting = restTemplate.getForObject(url, Item[].class);
return greeting;
} catch (Exception e) {
//Toast.makeText(getActivity(), "Error Loading !", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
protected void onPreExecute(){
progressDialog = new ProgressDialog(getActivity(),
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("chargement des elements...");
progressDialog.show();
}
#Override
protected void onPostExecute(Item[] greeting) {
Log.d("okokok",""+greeting.length);
progressDialog.dismiss();
}
}
And here is the class that I am using to deserialize:
public class Item {
private List<card_details> carte;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCat_id() {
return cat_id;
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getApp_id() {
return app_id;
}
public void setApp_id(String app_id) {
this.app_id = app_id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLft() {
return lft;
}
public void setLft(String lft) {
this.lft = lft;
}
public String getRgt() {
return rgt;
}
public void setRgt(String rgt) {
this.rgt = rgt;
}
public String getParent_cat_id() {
return parent_cat_id;
}
public void setParent_cat_id(String parent_cat_id) {
this.parent_cat_id = parent_cat_id;
}
public String getAdded_date() {
return added_date;
}
public void setAdded_date(String added_date) {
this.added_date = added_date;
}
public String getLast_edit_date() {
return last_edit_date;
}
public void setLast_edit_date(String last_edit_date) {
this.last_edit_date = last_edit_date;
}
public String getLanguage_id() {
return language_id;
}
public void setLanguage_id(String language_id) {
this.language_id = language_id;
}
public String getCategory_id() {
return category_id;
}
public void setCategory_id(String category_id) {
this.category_id = category_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getCustom_url() {
return custom_url;
}
public void setCustom_url(String custom_url) {
this.custom_url = custom_url;
}
public List<Detail_cartes> getCarte() {
return carte;
}
public void setCarte(List<Detail_cartes> carte) {
this.carte = carte;
}
public static class Detail_cartes{
private String nom_carte ;
private String prix ;
private String image ;
private String validity ;
}
}
JSONArray array=new JSONArray(your data);
JSONObject obj=array.getJSONObject(0);
JSONObject cardDetail=obj.getJSONObject("card_details");
Hii u can use the following code:
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}

Categories

Resources