How can I deseralize json object in java pojo class? - json

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.

Related

Android - How can I access nested objects?

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;
}
}

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());
}

deserialize gson object using GSONConverter

I need to deserialize a gson response
Here is the format.
{"lastid":"5", "testimonials":["a","b","c"]}
Pls suggest for DTO's and conversion.
public class TestimonialsOutputDTO implements Serializable {
public String lastid;
public List<TestimonialsDTO> testimonials;
public String getLastid() {
return lastid;
}
public void setLastid(String lastid) {
this.lastid = lastid;
}
public List<TestimonialsDTO> getTestimonials() {
return testimonials;
}
public void setTestimonials(List<TestimonialsDTO> testimonials) {
this.testimonials = testimonials;
}
}
and
public class TestimonialsDTO
{
public String testimonials;
public String getTestimonials() {
return testimonials;
}
public void setTestimonials(String testimonials) {
this.testimonials = testimonials;
}
}
You can parse "testimonials":["a","b","c"] in Java List directly instead of creating your own custom pojo.
Here your model class.
public class TestimonialsOutputDTO {
public String lastid;
public List<String> testimonials;
// getter/setter
// toString()
}

dropwizard: incorrect json resulting from group of items

I am using Dropwizard to deliver a RESTful service. The JSON I EXPECT looks like this:
{"featuredMerchants":
{"featuredMerchant":[
{"browseId":"v1_0_0_1112",
"merchantId":3902,
"priority":1,
"sourceId":"15"},
...,
{"browseId":"v1_0_0_1112",
"merchantId":456,
"priority":4,
"sourceId":"15"}]}}
But the JSON I am GETTING is this:
{"featuredMerchant":[
{"browseId":"v1_0_0_1112",
"merchantId":3902,
"priority":1,
"sourceId":"15"},
...,
{"browseId":"v1_0_0_1112",
"merchantId":456,
"priority":4,
"sourceId":"15"}]}
I have two classes. I have an ApiFeaturedMerchantGroup class that contains a list of ApiFeaturedMerchants.
#JsonRootName("featuredMerchants")
public class ApiFeaturedMerchantGroup {
private List<ApiFeaturedMerchant> apiFeaturedMerchants;
public ApiFeaturedMerchantGroup() {
}
#JsonProperty("featuredMerchant")
public List<ApiFeaturedMerchant> getApiFeaturedMerchants() { return apiFeaturedMerchants; }
public void setApiFeaturedMerchants(List<ApiFeaturedMerchant> apiFeaturedMerchants) { this.apiFeaturedMerchants = apiFeaturedMerchants; }
}
#JsonRootName("featuredMerchant")
public class ApiFeaturedMerchant {
private String browseId;
private int merchantId;
private Integer priority;
private String sourceId;
public ApiFeaturedMerchant() {
}
public String getBrowseId() { return browseId; }
public void setBrowseId(String browseId) { this.browseId = browseId; }
public int getMerchantId() { return merchantId; }
public void setMerchantId(int merchantId) { this.merchantId = merchantId; }
public Integer getPriority() { return priority; }
public void setPriority(Integer priority) { this.priority = priority; }
public String getSourceId() { return sourceId; }
public void setSourceId(String sourceId) { this.sourceId = sourceId; }
}
How do I get the extra level into my JSON, the "featuredMerchants" group that contains the individual "featuredMerchant" items? Do I have the wrong annotations, or am I missing one/some?
It's a setting on ObjectMapperFactory:
ObjectMapperFactory objectMapperFactory = new ObjectMapperFactory();
objectMapperFactory.enable(SerializationFeature.WRAP_ROOT_VALUE);
objectMapper = objectMapperFactory.build();

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.