Android - How can I access nested objects? - json

I know this question has been brought up quite often, but so far I didn't really find an answer...
I am trying to use Android with GSON. I want to use a JSON String to fill a Gridview but I dont know how to access the nested objects.
The JSON File:
[{'ProductCategories':[
{
'name':'Cat1', 'Product Series':[
{
'name':'ProdSeries1', 'Description':'Lorem Ipsum Bla Bla','Products':[
{
'name':'Product1','key':'value','key':'...'
},
{
'name':'Product2','key':'value','key':'...'
},
]
}
]
},
]
}]
I made 4 classes:Products,ProductSeries,ProductCatalog and ProductCategory.
example:
public class ProductCatalog {
#SerializedName("ProductCategories")
#Expose
private List<ProductCategory> productCategories = null;
public List<ProductCategory> getProductCategories() {
return productCategories;
}
public void setProductCategories(List<ProductCategory> productCategories) {
this.productCategories = productCategories;
}
}
After that I parsed the JSON with gson:
Gson gson = new Gson();
Type type = new TypeToken<List<ProductCatalog>>(){}.getType();
List<ProductCatalog> productcatalog = gson.fromJson(JSONstring,type);
Now I have a parsed list of the JSON data but dont know how to work with the nested objects like 'Product1'. I thought the getters would help, but I cant access getProductCategories() in my activity. How can I do that?

If your using Gson means This will help you
public class MainClazz {
#SerializedName("ProductCategories")
#Expose
private List<ProductCategory> productCategories = null;
public List<ProductCategory> getProductCategories() {
return productCategories;
}
public void setProductCategories(List<ProductCategory> productCategories) {
this.productCategories = productCategories;
}
}
public class Product {
#SerializedName("name")
#Expose
private String name;
#SerializedName("key")
#Expose
private String key;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
public class ProductCategory {
#SerializedName("name")
#Expose
private String name;
#SerializedName("Product Series")
#Expose
private List<ProductSeries> productSeries = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ProductSeries> getProductSeries() {
return productSeries;
}
public void setProductSeries(List<ProductSeries> productSeries) {
this.productSeries = productSeries;
}
}
public class ProductSeries {
#SerializedName("name")
#Expose
private String name;
#SerializedName("Description")
#Expose
private String description;
#SerializedName("Products")
#Expose
private List<Product> products = null;
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 List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}

Related

How to send values to parent table column in json

Customer entity
#Entity
#Table(name="Customer")
public class Customer {
#Id
#GeneratedValue
private Long cusId;
#Column(name="firstname")
private String firstName;
#Column(name="lastname")
private String lastName;
#Column(name="address")
private String add;
#Column(name="tel")
private int tel;
#Column(name="email")
private String email;
#Column(name="userName")
private String username;
#Column(name="password")
private String password;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "customer")
#JsonManagedReference
private List<Complain> complain=new ArrayList<Complain>();
public Customer() {
super();
// TODO Auto-generated constructor stub
}
public Long getCusId() {
return cusId;
}
public void setCusId(Long cusId) {
this.cusId = cusId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAdd() {
return add;
}
public void setAdd(String add) {
this.add = add;
}
public int getTel() {
return tel;
}
public void setTel(int tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Complain> getComplain() {
return complain;
}
public void setComplain(List<Complain> complain) {
this.complain = complain;
}
}
Complain Entity
#Entity
#Table(name="Complain")
public class Complain {
#Id
#GeneratedValue
private Long id;
#Column(name="repfirst")
private String repfirst;
#Column(name="replast")
private String replast;
#Column(name="warranty")
private String warranty;
#Column(name="dop")
private String purDate;
#Column(name="Nomachine")
private String Nomachine;
#Column(name="Complain")
private String Complain;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="cus_id", referencedColumnName = "cusId")
#JsonBackReference
private Customer customer;
public Complain() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRepfirst() {
return repfirst;
}
public void setRepfirst(String repfirst) {
this.repfirst = repfirst;
}
public String getReplast() {
return replast;
}
public void setReplast(String replast) {
this.replast = replast;
}
public String getWarranty() {
return warranty;
}
public void setWarranty(String warranty) {
this.warranty = warranty;
}
public String getPurDate() {
return purDate;
}
public void setPurDate(String purDate) {
this.purDate = purDate;
}
public String getNomachine() {
return Nomachine;
}
public void setNomachine(String nomachine) {
Nomachine = nomachine;
}
public String getComplain() {
return Complain;
}
public void setComplain(String complain) {
Complain = complain;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
I want to pass data to the mysql database through the postman tool. How can I pass value for the foreign key column through the json query?
This is the method I have used in controller
#PostMapping(path="/",consumes="application/json",produces="application/json")
public void addComplain(#RequestBody Complain complain)
{
Integer id = complainService.getAllComplain().size()+1;
complain.setId(new Long(id));
complainService.createOrUpdateComplain(complain); }
After I send the request from the postman, all the data are saved except the foreign key. I think I missed something in mapping two tables.
This is my json query
{"complain":"No power",
"repfirst":"hi",
"replast":"all",
"warranty":"yes",
"purDate":"2020-02-29",
"nomachine":"6",
"tel":"46544654",
"Customer":[
{"cusId":"1"}
]
}
Database table image
Please help, Thanks in advance
{
"repfirst": "",
"replast": "",
"warranty": "",
"purDate" : "",
"Nomachine": "",
"Complain": "",
"cus_id": 1
}
That should work
"Customer":[
{"cusId":"1"}
]
This would work if you had Set<Customer> customers converted to an array in json, for example.

PUT not working with SpringDataRest

So I am building a REST api using SpringDataRest both Get and Post are working but I don´t know whats wrong with the PUT.
This is the entity im using:
#Entity
#Table(name = "companies")
public class Company {
#Id
#Column(name="CompanyId", nullable=false, unique=true)
private String companyId;
#Column(name="Name", nullable=false)
private String name;
#Column(name="ContactName", nullable=false)
private String contactName;
#Column(name="ContactSurName")
private String contactSurname;
#Column(name="ContactEmail", nullable=false)
private String contactEmail;
#Column(name="ContactPhone")
private String contactPhone;
#Column(name="Enabled", nullable=false)
private String enabled;
#Column(name="Logo")
private String logo;
#Column(name = "CreationDate", columnDefinition="DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
#Column(name = "LastUpdateDate", columnDefinition="DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date lastUpdateDate;
//Region Constructors
private Company(){}
public Company(String companyId, String name, String contactName, String contactSurname, String contactEmail, String contactPhone,
String enabled){
this.companyId = companyId;
this.name = name;
this.contactName = contactName;
this.contactSurname = contactSurname;
this.contactEmail = contactEmail;
this.contactPhone = contactPhone;
this.enabled = enabled;
this.creationDate = new Date();
this.lastUpdateDate = new Date();
}
//EndRegion
//Region Getters & Setters
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactSurname() {
return contactSurname;
}
public void setContactSurname(String contactSurname) {
this.contactSurname = contactSurname;
}
public String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public String getContactPhone() {
return contactPhone;
}
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone;
}
public String getEnabled() {
return enabled;
}
public void setEnabled(String enabled) {
this.enabled = enabled;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getLastUpdateDate() {
return lastUpdateDate;
}
public void setLastUpdateDate(Date lastUpdateDate) {
this.lastUpdateDate = lastUpdateDate;
}
//EndRegion
}
When I execute this request:
REQUEST
I get this response:
{
"cause": {
"cause": null,
"message": "No content to map due to end-of-input\n at [Source: org.apache.catalina.connector.CoyoteInputStream#1130374; line: 1, column: 0]"
},
"message": "Could not read an object of type class com.wipma.application.domain.Company from the request!; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input\n at [Source: org.apache.catalina.connector.CoyoteInputStream#1130374; line: 1, column: 0]"
}
I can´t figure out whats wrong, I suspect its something related with some field mapping but cant sort it out.
Thanks in advance

Issue with deserializing nested json

I am working on deserializing the below JSON:
{"self":"http://members.cs.com/rest/api/user?username=abc#cs.com",
"key":"abc#cs.com",
"name":"abc#cs.com",
"emailAddress":"abc#cs.com",
"displayName":"ABC",
"active":true,
"members":{"size":1,"items":[{"name":"member-users","self":"http://members.cs.com/rest/api/user?username=abc#cs.com"}]},
"expand":"members"}
I have created the following classes:
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserList {
private String name;
private String emailAddress;
private String displayName;
private boolean active;
List<MemberName> members = new ArrayList<>();
#JsonCreator
public UserList(#JsonProperty("name") String name, #JsonProperty("emailAddress") String emailAddress, #JsonProperty("displayName") String displayName, #JsonProperty("active") boolean active, #JsonProperty("members") List<MemberName> members) {
this.name = name;
this.emailAddress = emailAddress;
this.displayName = displayName;
this.active = active;
this.members.addAll(groups);
}
//getters
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class MemberName {
private String name;
#JsonCreator
public MemberName(#JsonProperty("name") String name) {
this.name = name;
}
public String getName() {
return name;
}
}
When I don't give the members as a property the deserialization works fine and I can see the values for the name, displayName, active, emailAddress. The problem happens with the MemberName.
Could someone help with this?
This worked for me:
Class Items as below:
public class Items {
private String name;
private String self;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
}
Members class as below:
public class Members {
private int size;
private List<Items> items;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<Items> getItems() {
return items;
}
public void setItems(List<Items> items) {
this.items = items;
}
}
Data class as below:
public class Data {
private String self;
private String key;
private String name;
private String emailAddress;
private String displayName;
private boolean active;
private Members members;
private String expand;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Members getMembers() {
return members;
}
public void setMembers(Members members) {
this.members = members;
}
public String getExpand() {
return expand;
}
public void setExpand(String expand) {
this.expand = expand;
}
}
The deserialization as below:
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String jsonString = "{\"self\": \"http://members.cs.com/rest/api/user?username=abc#cs.com\",\"key\": \"abc#cs.com\",\"name\": \"abc#cs.com\","
+ "\"emailAddress\": \"abc#cs.com\",\"displayName\": \"ABC\",\"active\": true,\"members\": {\"size\": 1,\"items\": [{"
+ "\"name\": \"member-users\",\"self\": \"http://members.cs.com/rest/api/user?username=abc#cs.com\" }]},\"expand\": \"members\"}";
ObjectMapper mapper = new ObjectMapper();
Data obj = mapper.readValue(jsonString,Data.class);
System.out.println(obj.getSelf());
System.out.println(obj.getKey());
System.out.println(obj.getName());
System.out.println(obj.getEmailAddress());
System.out.println(obj.getDisplayName());
System.out.println(obj.isActive());
System.out.println(obj.getMembers().getSize());
System.out.println(obj.getMembers().getItems().get(0).getName());
System.out.println(obj.getMembers().getItems().get(0).getSelf());
System.out.println(obj.getExpand());
}

issue in JSON parsing by GSON

I have Issue in JSON Parsing by GSON
my JSONERESPONSE is
{"services":[{"service":{"name":"asd","id":"1"}},
{"service":{"name":"asdf","id":"2"}},
{"service":{"name":"asdfg","id":"3"}}]}
How to parse this response?
means I have issue in creating class of above response
I have created service class but i am confusing in how to create services class.
public class services {
#SerializedName("service")
ArrayList<service> list;
public services(){
System.out.println("services constructor stuff");
list= new ArrayList<service>();
}
/**
* #return the list
*/
public ArrayList<service> getList() {
return list;
}
/**
* #param list the list to set
*/
public void setList(ArrayList<service> list) {
this.list = list;
}
}
but getting 0 in getList();
Note: I can not change the response, so don't suggest it
Thank you
Ok, we need to create a middle layer class to make it right.
Services.java
public class Services {
private ArrayList<ServiceWrapper> services = new ArrayList<ServiceWrapper>();
public ArrayList<ServiceWrapper> getServices() {
return services;
}
public void setServices(ArrayList<ServiceWrapper> services) {
this.services = services;
}
}
ServiceWrapper.java
public class ServiceWrapper {
private Service service;
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
}
Service.java
public class Service {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The following is testing code
Gson gson = new Gson();
String s = "{\"services\":[{\"service\":{\"name\":\"asd\",\"id\":\"1\"}},{\"service\":{\"name\":\"asdf\",\"id\":\"2\"}},{\"service\":{\"name\":\"asdfg\",\"id\":\"3\"}}]}";
Services services = gson.fromJson(s, Services.class);
for(ServiceWrapper serviceWrapper : services.getServices()){
System.out.println(serviceWrapper.getService().getId());
System.out.println(serviceWrapper.getService().getName());
}
Services.java
public class Services {
private List<Service> services;
public List<Service> getServiceList() {
return services;
}
public void setServiceList(List<Service> services) {
this.services = services;
}
}
Service.java
public class Service {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
your json parsing logic goes here:
Gson gson = new Gson();
String s = "{\"services\":[{\"service\":{\"name\":\"asd\",\"id\":\"1\"}},{\"service\":{\"name\":\"asdf\",\"id\":\"2\"}},{\"service\":{\"name\":\"asdfg\",\"id\":\"3\"}}]}";
Services services = gson.fromJson(s, Services.class);
Basically, the json string is not a simple json array format, it is actually a json array inside a json object. So it implies that you need two Class, one represents each item inside json array - Service.java and another plays as a wrapper holding a list of items.

How can I deseralize json object in java pojo class?

I have a simple JSON statement which type is very per need. like this
{
actor:{name:"kumar",mbox:"kumar#gmail.com"}
verb :"completed"
}
or
{
actor:{name:["kumar","manish"],mbox:["kumar#gmail.com","manish#gmail.com"]}
verb :{
"id" : "http://adlnet.gov/expapi/verbs/completed",
"display" : {
"en-US" : "completed"
}
}
I am using using POJO class to map this json string and pojo class code is given bleow
#JsonProperty("actor")
Actor actor;
#JsonProperty("verb")
Verb objVerb;
#JsonProperty("verb")
String verb;
public Actor getActor() {
return actor;
}
public void setActor(Actor actor) {
this.actor = actor;
}
public Verb getObjVerb() {
return objVerb;
}
public void setObjVerb(Verb objVerb) {
this.objVerb = objVerb;
}
#JsonIgnore
public String getVerb() {
return verb;
}
#JsonIgnore
public void setVerb(String verb) {
this.verb = verb;
}
public static class Actor {
String objectType;
#JsonProperty("name")
ArrayList<String> listName;
#JsonProperty("name")
String name;
#JsonProperty("mbox")
ArrayList<String> listMbox;
#JsonProperty("mbox")
String mbox;
#JsonProperty("mbox_sha1sum")
ArrayList<String> Listmbox_sha1sum;
#JsonProperty("mbox_sha1sum")
String mbox_sha1sum;
#JsonProperty("openid")
String openid;
#JsonProperty("account")
Account account;
public String getObjectType() {
return objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
public ArrayList<String> getListName() {
return listName;
}
public void setListName(ArrayList<String> listName) {
this.listName = listName;
}
#JsonIgnore
public String getName() {
return name;
}
#JsonIgnore
public void setName(String name) {
this.name = name;
}
public ArrayList<String> getListMbox() {
return listMbox;
}
public void setListMbox(ArrayList<String> listMbox) {
this.listMbox = listMbox;
}
#JsonIgnore
public String getMbox() {
return mbox;
}
#JsonIgnore
public void setMbox(String mbox) {
this.mbox = mbox;
}
public ArrayList<String> getListmbox_sha1sum() {
return Listmbox_sha1sum;
}
public void setListmbox_sha1sum(ArrayList<String> listmbox_sha1sum) {
Listmbox_sha1sum = listmbox_sha1sum;
}
#JsonIgnore
public String getMbox_sha1sum() {
return mbox_sha1sum;
}
#JsonIgnore
public void setMbox_sha1sum(String mbox_sha1sum) {
this.mbox_sha1sum = mbox_sha1sum;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public static class Account {
#JsonProperty("homePage")
String homePage;
#JsonProperty("name")
String name;
public String getHomePage() {
return homePage;
}
public void setHomePage(String homePage) {
this.homePage = homePage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
public static class Verb {
String id;
Map<String,String> display;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, String> getDisplay() {
return display;
}
public void setDisplay(Map<String, String> display) {
this.display = display;
}
}
I am using jaxb and jakson. I am implementing the webservice to handle the json statement
so I use the bean class to map with json. But when I use to map this json then it gives the following exceptions
org.codehaus.jackson.map.JsonMappingException : property with the name "mbox" have two entry.
Define a proper bean structure so it directly mapped to the beans class
Try to leave only #JsonProperty("mbox") ArrayList<String> listMbox; field (don't need #JsonProperty("mbox")
String mbox;)
and add Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY=true to Jackson object mapper config.
So in deserialization it will be able to get as both array and single element.
you can use gson.
class cls = gson.fromJson(jsonString, clazz);
here jsonString can be stringified java script object. gson.fromJson method can map your java script key to java property.