deserialize gson object using GSONConverter - json

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

Related

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

GSON throwing “Expected BEGIN_OBJECT but was STRING

This is Json Object
[
{
"UserId":"demouser1",
"Catagories":[
{
"CatagoryName":"Entertainment",
"Persent":"25"
},
{
"CatagoryName":"Household",
"Persent":"25"
},
{
"CatagoryName":"Movie",
"Persent":"25"
},
{
"CatagoryName":"Misc",
"Persent":"25"
}
],
"RequestId":null,
"ResponseStatus":false,
"Token":null
}
]
Used The Following approach to parse the above Json
public class CategoryEntity {
private String CatagoryName;
private String Persent;
public String getCatagoryName() {
return CatagoryName;
}
public void setCatagoryName(String catagoryName) {
CatagoryName = catagoryName;
}
public String getPersent() {
return Persent;
}
public void setPersent(String persent) {
Persent = persent;
}
}
import java.util.List;
public class Entity {
private String UserId;
public String getUserId() {
return UserId;
}
public void setUserId(String userId) {
UserId = userId;
}
public List<CategoryEntity> getListCatagories() {
return ListCatagories;
}
public void setListCatagories(List<CategoryEntity> listPMMCatagories) {
ListCatagories = listPMMCatagories;
}
public String getRequestId() {
return RequestId;
}
public void setRequestId(String requestId) {
RequestId = requestId;
}
public boolean isResponseStatus() {
return ResponseStatus;
}
public void setResponseStatus(boolean responseStatus) {
ResponseStatus = responseStatus;
}
private List<CategoryEntity> ListCatagories;
private String RequestId;
private String Token;
public String getToken() {
return Token;
}
public void setToken(String token) {
Token = token;
}
private boolean ResponseStatus;
}
And
Following approach to convert the json object to corresponding object
Gson gson =new Gson();
JsonPrimitive listCatagoriesElement= element.getAsJsonPrimitive();
System.out.println("listCatagoriesElement.getAsString()>>"+listCatagoriesElement.getAsString());
sysout prints: listCatagoriesElement.getAsString()>>[{"UserId":"user1","ListCatagories":[{"CatagoryName":"Entertainment","Persent":"25"},{"CatagoryName":"Household","Persent":"25"},{"CatagoryName":"Movie","Persent":"25"},{"CatagoryName":"Misc","Persent":"25"}],"RequestId":null,"ResponseStatus":false,"Token":null}]
Entity entity = gson.fromJson(listCatagoriesElement, Entity.class);
Any ideas how should I fix it?
Thanks!
Your class CategoryEntity is correct, but in your class Entity, the attribute ListCatagories should be called Catagories to match the name in the JSON!
Apart from that, in order to parse the JSON you'd better do something like this:
Gson gson = new Gson();
Type listType = new TypeToken<List<Entity>>() {}.getType();
List<Entity> entities = gson.fromJson(yourJsonString, listType);
So you'll have a List containing just one Entity object, and you can access the values just with:
String catagoryNameI = entities.get(0).getCatagories().get(i).getCatagoryName();
String persentI = entities.get(0).getCatagories().get(i).getPersent();
You have to do this because your whole JSON response is an array, surrounded by [ ... ], so you need to parse it into some List...

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.

Unable to deserialize Json string to POJO (using GSON)

Any idea why the JSON won't map to the java object?
The code..
String result = "{\"outerclass\":{\"innerclass\":{\"booleanA\":true,\"stringB\":\"b\",\"stringC\":\"c\"}}}\n";
Gson gson = new Gson();
TempObject o = gson.fromJson(result,TempObject.class);
The POJO..
public class TempObject {
public static class outerclass {
public static class innerclass {
public static boolean booleanA;
public static String stringB;
public static String stringC;
}
}
}
OTher example..
String result = "{\"idata\":{\"result\":{\"error\":true,\"errorMessage\":\"Invalid username and/or password\",\"requestTime\":\"2011-08-26T18:39:02Z\"}}}";
Gson gson = new Gson();
UserData d = gson.fromJson(result, UserData.class);
Class..
public class UserData {
idata data;
public static class idata {
result res;
public static class result {
public boolean error;
public String errorMessage;
public String requestTime;
}
}
}
If I am not mistaken, that's because all of your fields are static, those not related to each separate object.
So I think the class should look like that:
public class TempObject {
Outerclass outerclass;
public static class Outerclass {
Innerclass innerclass;
public static class Innerclass {
public boolean booleanA;
public String stringB;
public String stringC;
}
}
}
For example, on my machine, the output of:
public class Example{
public static void main(String[] args) {
String result = "{\"outerclass\":{\"innerclass\":{\"booleanA\":true,\"stringB\":\"b\",\"stringC\":\"c\"}}}\n";
Gson gson = new Gson();
TempObject o = gson.fromJson(result, TempObject.class);
System.out.println(gson.toJson(o));
}
public static class TempObject {
Outerclass outerclass;
public static class Outerclass {
Innerclass innerclass;
public static class Innerclass {
public boolean booleanA;
public String stringB;
public String stringC;
}
}
}
}
Is:
{"outerclass":{"innerclass":{"booleanA":true,"stringB":"b","stringC":"c"}}}
You are unable to deserialize because the variable names are not matching with the keys in your Json. In your second example
String result = "{\"idata\":{\"result\":{\"error\":true,\"errorMessage\":\"Invalid username and/or password\",\"requestTime\":\"2011-08-26T18:39:02Z\"}}}";
idata data;
result res;
The object names should match with the keys in JSON but not class names.
IData idata;
Result result;