JAXB XML Unmarshaller error. Getting null value for all Object - java

I get the following error when I tried to parse the below string
<?xml version="1.0" encoding="UTF-8"?>
<CC5Response>
<OrderId>ORDER-17305KXSH11966</OrderId>
<GroupId>ORDER-173053333KXSH11966</GroupId>
<Response>Approved</Response>
<AuthCode>0293333584</AuthCode>
<HostRefNum>73051033333011833</HostRefNum>
<ProcReturnCode>00</ProcReturnCode>
<TransId>17305K33245XSH11968</TransId>
<ErrMsg></ErrMsg>
<Extra>
<SETTLEID>1</SETTLEID>
<TRXDATE>20171101 10:23:18</TRXDATE>
<ERRORCODE></ERRORCODE>
<CARDBRAND>VISA</CARDBRAND>
<CARDISSUER>CDM</CARDISSUER>
<NUMCODE>00</NUMCODE>
</Extra>
</CC5Response>
Code snippet for Unmarshalling is given below
JAXBContext jaxbContext = JAXBContext.newInstance(CC5Response.class);
XMLInputFactory xif = XMLInputFactory.newFactory();
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
XMLStreamReader xsr = xif.createXMLStreamReader(IOUtils.toInputStream(sb.toString(), "UTF-8"));
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
CC5Response res = (CC5Response) jaxbUnmarshaller.unmarshal(xsr);
System.out.println("*************"+res.toString());
bean class is given below
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType
#XmlRootElement(name = "CC5Response")
public class CC5Response {
#XmlAttribute
private String ProcReturnCode;
// #XmlAttribute
// private Extra Extra;
/*public Extra getExtra() {
return Extra;
}
public void setExtra(Extra extra) {
Extra = extra;
}*/
#XmlAttribute
private String AuthCode;
#XmlAttribute
private String OrderId;
#XmlAttribute
private String TransId;
#XmlAttribute
private String ErrMsg;
#XmlAttribute
private String Response;
#XmlAttribute
private String HostRefNum;
#XmlAttribute
private String GroupId;
I always get a plain object with null values.

To enable JAXB unmarshaller to work fine, you should simulate your XML into right structure of JAVA classes ... Follow the following steps and it will work with you.
Your XML should be like :
<?xml version="1.0" encoding="UTF-8"?>
<CC5Response>
<OrderId>ORDER-17305KXSH11966</OrderId>
<GroupId>ORDER-173053333KXSH11966</GroupId>
<Response>Approved</Response>
<AuthCode>0293333584</AuthCode>
<HostRefNum>73051033333011833</HostRefNum>
<ProcReturnCode>00</ProcReturnCode>
<TransId>17305K33245XSH11968</TransId>
<ErrMsg>error message</ErrMsg>
<Extra>
<SETTLEID>1</SETTLEID>
<TRXDATE>20171101 10:23:18</TRXDATE>
<ERRORCODE>0000</ERRORCODE>
<CARDBRAND>VISA</CARDBRAND>
<CARDISSUER>CDM</CARDISSUER>
<NUMCODE>00</NUMCODE>
</Extra>
</CC5Response>
We will create 2 necessary classes in Java :
2.1 create class named "CC5Response.java" like :
#XmlRootElement(name = "CC5Response")
public class CC5Response {
private String ProcReturnCode;
private String AuthCode;
private String OrderId;
private String TransId;
private String ErrMsg;
private String Response;
private String HostRefNum;
private String GroupId;
private List<Extra> Extra;
/**
* #return the ProcReturnCode
*/
#XmlElement(name="ProcReturnCode")
public String getProcReturnCode() {
return ProcReturnCode;
}
/**
* #param ProcReturnCode the ProcReturnCode to set
*/
public void setProcReturnCode(String ProcReturnCode) {
this.ProcReturnCode = ProcReturnCode;
}
/**
* #return the AuthCode
*/
#XmlElement(name="AuthCode")
public String getAuthCode() {
return AuthCode;
}
/**
* #param AuthCode the AuthCode to set
*/
public void setAuthCode(String AuthCode) {
this.AuthCode = AuthCode;
}
/**
* #return the OrderId
*/
#XmlElement(name="OrderId")
public String getOrderId() {
return OrderId;
}
/**
* #param OrderId the OrderId to set
*/
public void setOrderId(String OrderId) {
this.OrderId = OrderId;
}
/**
* #return the TransId
*/
#XmlElement(name="TransId")
public String getTransId() {
return TransId;
}
/**
* #param TransId the TransId to set
*/
public void setTransId(String TransId) {
this.TransId = TransId;
}
/**
* #return the ErrMsg
*/
#XmlElement(name="ErrMsg")
public String getErrMsg() {
return ErrMsg;
}
/**
* #param ErrMsg the ErrMsg to set
*/
public void setErrMsg(String ErrMsg) {
this.ErrMsg = ErrMsg;
}
/**
* #return the Response
*/
#XmlElement(name="Response")
public String getResponse() {
return Response;
}
/**
* #param Response the Response to set
*/
public void setResponse(String Response) {
this.Response = Response;
}
/**
* #return the HostRefNum
*/
#XmlElement(name="HostRefNum")
public String getHostRefNum() {
return HostRefNum;
}
/**
* #param HostRefNum the HostRefNum to set
*/
public void setHostRefNum(String HostRefNum) {
this.HostRefNum = HostRefNum;
}
/**
* #return the GroupId
*/
#XmlElement(name="GroupId")
public String getGroupId() {
return GroupId;
}
/**
* #param GroupId the GroupId to set
*/
public void setGroupId(String GroupId) {
this.GroupId = GroupId;
}
/**
* #return the Extra
*/
#XmlElement(name="Extra")
public List<Extra> getExtra() {
return Extra;
}
/**
* #param Extra the Extra to set
*/
public void setExtra(List<Extra> Extra) {
this.Extra = Extra;
}
}
2.2 create class named "Extra.java" like :
public class Extra {
private String SETTLEID;
private String TRXDATE;
private String ERRORCODE;
private String CARDBRAND;
private String CARDISSUER;
private String NUMCODE;
/**
* #return the SETTLEID
*/
public String getSETTLEID() {
return SETTLEID;
}
/**
* #param SETTLEID the SETTLEID to set
*/
public void setSETTLEID(String SETTLEID) {
this.SETTLEID = SETTLEID;
}
/**
* #return the TRXDATE
*/
public String getTRXDATE() {
return TRXDATE;
}
/**
* #param TRXDATE the TRXDATE to set
*/
public void setTRXDATE(String TRXDATE) {
this.TRXDATE = TRXDATE;
}
/**
* #return the ERRORCODE
*/
public String getERRORCODE() {
return ERRORCODE;
}
/**
* #param ERRORCODE the ERRORCODE to set
*/
public void setERRORCODE(String ERRORCODE) {
this.ERRORCODE = ERRORCODE;
}
/**
* #return the CARDBRAND
*/
public String getCARDBRAND() {
return CARDBRAND;
}
/**
* #param CARDBRAND the CARDBRAND to set
*/
public void setCARDBRAND(String CARDBRAND) {
this.CARDBRAND = CARDBRAND;
}
/**
* #return the CARDISSUER
*/
public String getCARDISSUER() {
return CARDISSUER;
}
/**
* #param CARDISSUER the CARDISSUER to set
*/
public void setCARDISSUER(String CARDISSUER) {
this.CARDISSUER = CARDISSUER;
}
/**
* #return the NUMCODE
*/
public String getNUMCODE() {
return NUMCODE;
}
/**
* #param NUMCODE the NUMCODE to set
*/
public void setNUMCODE(String NUMCODE) {
this.NUMCODE = NUMCODE;
}
}
Main Method should be like :
/**
* #param args the command line arguments
* #throws javax.xml.bind.JAXBException
*/
public static void main(String[] args) throws JAXBException {
// TODO code application logic here
try {
File file = new File("file.xml");
if (file.exists()) {
JAXBContext jaxbContext = JAXBContext.newInstance(CC5Response.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
CC5Response response = (CC5Response) jaxbUnmarshaller.unmarshal(file);
if (response != null) {
System.out.println("*************" + response.getAuthCode());
System.out.println("*************" + response.getErrMsg());
System.out.println("*************" + response.getGroupId());
System.out.println("*************" + response.getOrderId());
System.out.println("*************" + response.getResponse());
//you can get any field from Exta class
System.out.println("*************" + response.getExtra());
}
}
} catch (JAXBException e) {
e.printStackTrace();
}
}

Related

Gson.fromJson(json, Custom.class) empty string

i'm developing a small web application.
That's my problem:
This is executed when a user try to add a new record in my Datatable
#RequestMapping(value="/saveJokerRule", method= RequestMethod.POST, consumes= "application/json", produces = "application/json")
#ResponseBody
public String saveJokerRule(#RequestBody String json) {
System.out.println("JSON EDITOR:" + json.toString());
EditorResponse editorResponse = new EditorResponse();
JokerRuleForm jokerRuleForm = new GsonBuilder().serializeNulls().create().fromJson(json, JokerRuleForm.class);
...
}
This is the valid json received by the server and printed by a System call:
{"action":"create","data":{"0":{"jokerRule":{"group":1,"campaignPhase":"","dailyLimit":"","weeklyLimit":"","monthlyLimit":"","validFrom":"","activity":1}}}}
That's the JokerRuleForm classs
public class JokerRuleForm {
#Expose
String action;
#Expose
#SerializedName("data")
Map<String, JokerRuleView> data;
...
}
That's the JokerRuleView class
public class JokerRuleView {
String idJokerRule;
private AgentGroup group;
private JokerRule jokerRule;
private Activity activity;
public class JokerRule{
private String campaignPhase;
private Integer dailyLimit;
private Integer weeklyLimit;
private Integer monthlyLimit;
private Date validFrom;
private Date dateUpdate;
private String group;
private String activity;
/**
* #return the campaignPhase
*/
public String getCampaignPhase() {
return campaignPhase;
}
/**
* #param campaignPhase the campaignPhase to set
*/
public void setCampaignPhase(String campaignPhase) {
this.campaignPhase = campaignPhase;
}
/**
* #return the dailyLimit
*/
public Integer getDailyLimit() {
return dailyLimit;
}
/**
* #param dailyLimit the dailyLimit to set
*/
public void setDailyLimit(Integer dailyLimit) {
this.dailyLimit = dailyLimit;
}
/**
* #return the weeklyLimit
*/
public Integer getWeeklyLimit() {
return weeklyLimit;
}
/**
* #param weeklyLimit the weeklyLimit to set
*/
public void setWeeklyLimit(Integer weeklyLimit) {
this.weeklyLimit = weeklyLimit;
}
/**
* #return the monthlyLimit
*/
public Integer getMonthlyLimit() {
return monthlyLimit;
}
/**
* #param monthlyLimit the monthlyLimit to set
*/
public void setMonthlyLimit(Integer monthlyLimit) {
this.monthlyLimit = monthlyLimit;
}
/**
* #return the validFrom
*/
public Date getValidFrom() {
return validFrom;
}
/**
* #param validFrom the validFrom to set
*/
public void setValidFrom(Date validFrom) {
this.validFrom = validFrom;
}
/**
* #return the dateUpdate
*/
public Date getDateUpdate() {
return dateUpdate;
}
/**
* #param dateUpdate the dateUpdate to set
*/
public void setDateUpdate(Date dateUpdate) {
this.dateUpdate = dateUpdate;
}
/**
* #return the group
*/
public String getGroup() {
return group;
}
/**
* #param group the group to set
*/
public void setGroup(String group) {
this.group = group;
}
/**
* #return the activity
*/
public String getActivity() {
return activity;
}
/**
* #param activity the activity to set
*/
public void setActivity(String activity) {
this.activity = activity;
}
}
public class Activity {
String idActivity;
String name;
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the idGroup
*/
public String getIdActivity() {
return idActivity;
}
/**
* #param idGroup the idGroup to set
*/
public void setIdActivity(String idActivity) {
this.idActivity = idActivity;
}
}
public class AgentGroup {
String idGroup;
String name;
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the idGroup
*/
public String getIdGroup() {
return idGroup;
}
/**
* #param idGroup the idGroup to set
*/
public void setIdGroup(String idGroup) {
this.idGroup = idGroup;
}
}
/**
* #return the idJokerRule
*/
public String getIdJokerRule() {
return idJokerRule;
}
/**
* #param idJokerRule the idJokerRule to set
*/
public void setIdJokerRule(String idJokerRule) {
this.idJokerRule = idJokerRule;
}
/**
* #return the agentGroup
*/
public AgentGroup getGroup() {
return group;
}
/**
* #param agentGroup the agentGroup to set
*/
public void setGroup(AgentGroup group) {
this.group = group;
}
/**
* #return the jokerRule
*/
public JokerRule getJokerRule() {
return jokerRule;
}
/**
* #param jokerRule the jokerRule to set
*/
public void setJokerRule(JokerRule jokerRule) {
this.jokerRule = jokerRule;
}
/**
* #return the activity
*/
public Activity getActivity() {
return activity;
}
/**
* #param activity the activity to set
*/
public void setActivity(Activity activity) {
this.activity = activity;
}
}
JokerRuleForm jokerRuleForm = new GsonBuilder().serializeNulls().create().fromJson(json, JokerRuleForm.class);
When executing this line i got a NumberFormatException empty string and i think it dailyLimit's or date's fault because it's empty and fromJson() method can't do what he need to do.
I've read something about a TypeAdapter that seems can fit to my case, but i don't really know how to proceed and i'm not sure is a valid solution.
Can someone help me?
The limit fields e.g. dailyLimit are empty strings in your JSON. This was suggested in JsonParseException when encountering an empty value for an int or long #472 issue but Gson team closed it because it makes no sense to parse "" as int.
One of the users provided a solution in his comment which allows to leniently parse the number values. I'd not go this route myself and fix JSON instead, but it's up to you:
public static final TypeAdapter<Number> UNRELIABLE_INTEGER = new TypeAdapter<Number>() {
#Override
public Number read(JsonReader in) throws IOException {
JsonToken jsonToken = in.peek();
switch (jsonToken) {
case NUMBER:
case STRING:
String s = in.nextString();
try {
return Integer.parseInt(s);
} catch (NumberFormatException ignored) {
}
try {
return (int)Double.parseDouble(s);
} catch (NumberFormatException ignored) {
}
return null;
case NULL:
in.nextNull();
return null;
case BOOLEAN:
in.nextBoolean();
return null;
default:
throw new JsonSyntaxException("Expecting number, got: " + jsonToken);
}
}
#Override
public void write(JsonWriter out, Number value) throws IOException {
out.value(value);
}
};
public static final TypeAdapterFactory UNRELIABLE_INTEGER_FACTORY = TypeAdapters.newFactory(int.class, Integer.class, UNRELIABLE_INTEGER);
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(UNRELIABLE_INTEGER_FACTORY)
.create();

"No suitable constructor found for type" and the type exists and has a default constructor

I am receiving this message in a new jersey 1.19.4 app that I am building:
No suitable constructor found for type [simple type, class javax.xml.bind.JAXBElement<com.objex.idms.idd.types.IDDModule>]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: org.apache.catalina.connector.CoyoteInputStream#5a5e4ec1; line: 1, column: 2]
After much searching I have seen many posts that indicate this can be caused by a missing default constructor. However that doesn't seem to the the case here. Note I have tried this implementing "Serializable" with the same result. I am sure it's something simple but am just missing it.
Here is the class in question, any thoughts you might have would be appreciated.
package com.objex.idms.idd.types;
// import java.io.Serializable;
public class IDDModule {
/**
*
*/
//private static final long serialVersionUID = 1897236478938746827L;
private String DictName;
private String DictNode;
private String Name;
private String Version;
private String Language;
private String ModuleMetadata;
private String ModuleSource;
private String Message;
public IDDModule() {
}
/**
* #param dictName the dictName to set
*/
public void setDictName(String DictName) {
this.DictName = DictName;
}
/**
* #return the dictName
*/
public String getDictName() {
return DictName;
}
/**
* #param DictNode the dictNode to set
*/
public void setDictNode(String DictNode) {
this.DictNode = DictNode;
}
/**
* #return the dictNode
*/
public String getDictNode() {
return DictNode;
}
/**
* #param language the language to set
*/
public void setLanguage(String language) {
this.Language = language;
}
/**
* #return the language
*/
public String getLanguage() {
return Language;
}
/**
* #param Message the message to set
*/
public void setMessage(String Message) {
this.Message = Message;
}
/**
* #return the message
*/
public String getMessage() {
return Message;
}
/**
* #param ModuleMetadata the moduleMetadata to set
*/
public void setModuleMetadata(String ModuleMetadata) {
this.ModuleMetadata = ModuleMetadata;
}
/**
* #return the ModuleMetadata
*/
public String getModuleMetadata() {
return ModuleMetadata;
}
/**
* #param ModuleSource the moduleSource to set
*/
public void setModuleSource(String ModuleSource) {
this.ModuleSource = ModuleSource;
}
/**
* #return the moduleSource
*/
public String getModuleSource() {
return ModuleSource;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.Name = name;
}
/**
* #return the name
*/
public String getName() {
return Name;
}
/**
* #param version the version to set
*/
public void setVersion(String version) {
this.Version = version;
}
/**
* #return the version
*/
public String getVersion() {
return Version;
}
}

Volley parsing Json response is null Android

I am trying to parse JSON Object using volley but it is giving all the values as null
I am using GsonRequest custom class to parse using GSON library
public class GsonRequest < T > extends JsonRequest < T > {
/** Charset for request. */
private static final String PROTOCOL_CHARSET = "utf-8";
/** Content type for request. */
private static final String PROTOCOL_CONTENT_TYPE = String.format("application/json; charset=%s", PROTOCOL_CHARSET);
private final Gson mGson;
//private final String mBody;
private final Class < T > clazz;
private final Listener < T > listener;
private final Map < String,
String > headers;
private final String mBody;
public GsonRequest(int method, String url, String body, Class < T > clazz, Map < String, String > headers, Response.Listener < T > listener, Response.ErrorListener errorListener) {
super(method, url, (body == null) ? null: body, listener, errorListener);
this.clazz = clazz;
this.mBody = body;
this.headers = headers;
this.listener = listener;
mGson = new Gson();
}#Override
public Map < String,
String > getHeaders() throws AuthFailureError {
return headers != null ? headers: super.getHeaders();
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response < T > parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(mGson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
} catch(UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch(JsonSyntaxException e) {
Log.e("JsonSyntaxException", " " + e);
return Response.error(new ParseError(e));
}
}
}
I have created model class using http://www.jsonschema2pojo.org/ below is my model class
public class ModelConnection {
private List < Datum > data = new ArrayList < Datum > ();
private Integer code;
private Object message;
private Map < String,
Object > additionalProperties = new HashMap < String,
Object > ();
/**
*
* #return
* The data
*/
public List < Datum > getData() {
return data;
}
/**
*
* #param data
* The Data
*/
public void setData(List < Datum > data) {
this.data = data;
}
/**
*
* #return
* The code
*/
public Integer getCode() {
return code;
}
/**
*
* #param code
* The Code
*/
public void setCode(Integer code) {
this.code = code;
}
/**
*
* #return
* The message
*/
public Object getMessage() {
return message;
}
/**
*
* #param message
* The Message
*/
public void setMessage(Object message) {
this.message = message;
}
public Map < String,
Object > getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public class Datum {
private Integer userID;
private String firstName;
private String lastName;
private String title;
private String organization;
private String industry;
private String location;
private String profileSummary;
private String imagePath;
private List < Object > interests = new ArrayList < Object > ();
private Map < String,
Object > additionalProperties = new HashMap < String,
Object > ();
/**
*
* #return
* The userID
*/
public Integer getUserID() {
return userID;
}
/**
*
* #param userID
* The UserID
*/
public void setUserID(Integer userID) {
this.userID = userID;
}
/**
*
* #return
* The firstName
*/
public String getFirstName() {
return firstName;
}
/**
*
* #param firstName
* The FirstName
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
*
* #return
* The lastName
*/
public String getLastName() {
return lastName;
}
/**
*
* #param lastName
* The LastName
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The Title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The organization
*/
public String getOrganization() {
return organization;
}
/**
*
* #param organization
* The Organization
*/
public void setOrganization(String organization) {
this.organization = organization;
}
/**
*
* #return
* The industry
*/
public String getIndustry() {
return industry;
}
/**
*
* #param industry
* The Industry
*/
public void setIndustry(String industry) {
this.industry = industry;
}
/**
*
* #return
* The location
*/
public String getLocation() {
return location;
}
/**
*
* #param location
* The Location
*/
public void setLocation(String location) {
this.location = location;
}
/**
*
* #return
* The profileSummary
*/
public String getProfileSummary() {
return profileSummary;
}
/**
*
* #param profileSummary
* The ProfileSummary
*/
public void setProfileSummary(String profileSummary) {
this.profileSummary = profileSummary;
}
/**
*
* #return
* The imagePath
*/
public String getImagePath() {
return imagePath;
}
/**
*
* #param imagePath
* The ImagePath
*/
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
/**
*
* #return
* The interests
*/
public List < Object > getInterests() {
return interests;
}
/**
*
* #param interests
* The Interests
*/
public void setInterests(List < Object > interests) {
this.interests = interests;
}
public Map < String,
Object > getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
}
This is the response from rest client
{
-"Data": [2]
-0: {
"UserID": 124
"FirstName": "Mixer"
"LastName": "Development"
"Title": "Flipdex Architect "
"Organization": "CoStrategix"
"Industry": "Software "
"Location": "Bengaluru Area, India"
"ProfileSummary": "Mixer#^*+~|Software engineer?????????? 123456789"#&$)(;:/-.,?!ASDFZgZhXjZkZlZXCVZbNZmQWERTYUIOZp[]{}#%^*+¥£€><~|\_.,?! "
"ImagePath": "https://media.licdn.com/mpr/mprx/0_tiUBxkxpFtDhAIKrczfJBnzj6FMhlWiAOiiJJAUpF8YTlJayP3DBA3Mp5NrycIrrczfJ48nymk-3-DwljKYwBKBKIk-8-DErYKYNylCgh5F24Rlu-3HVpLuuwAHKUDj3c1VURiTsxsU"
"Interests": [0]
}
-1: {
"UserID": 153
"FirstName": "Mixer"
"LastName": "Android"
"Title": "Assistant Manager at CoStrategix"
"Organization": "CoStrategix"
"Industry": "Software"
"Location": "Bengaluru Area, India"
"ProfileSummary": "We have worked with over 35+ product companies and bring the critical thinking and technology expertise to launching your product. We have l"
"ImagePath": "https://media.licdn.com/mpr/mprx/0_0EwKKqh9nkV0X1t3pmPYj6B9ncH0T_TTJy0K9h29KnTYT1u8zElOR_C9q3zGb1gDJyjY4_SnOQUOGFf8zJmuZhhsUQUxGFHTzJmPP3zBKbm1HA1jMe4j1vRQR1T7wFxKysoyq1W3CaQ"
"Interests": [0]
}
"Code": 1
"Message": null
}
finally this is the way I am calling the api
GsonRequest request = new GsonRequest(Request.Method.GET, newConnectionAPI,null, ModelConnection.class, getHeaders(),
new Response.Listener<ModelConnection>() {
#Override
public void onResponse(ModelConnection response) {
if (listener != null) {
listener.networkResponseSuccessful(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("volley error", "" + error);
}
});
request.setTag(tag);
request.setRetryPolicy(new DefaultRetryPolicy(15000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(request);
when I debug I get all the values as null
Can anyone please help me out
Thought of answering my own question, may be someone can get help through this...
I created my Model class using jsonschema2pojo where I had to select JSON along with GSON(Which I forgot to select).
you can see the difference if you compare the Model classes posted above and below
public class ModelConnection {
#SerializedName("Data")#Expose
private List < Datum > data = new ArrayList < Datum > ();#SerializedName("Code")#Expose
private Integer code;#SerializedName("Message")#Expose
private Object message;
private Map < String,
Object > additionalProperties = new HashMap < String,
Object > ();
/**
*
* #return
* The data
*/
public List < Datum > getData() {
return data;
}
/**
*
* #param data
* The Data
*/
public void setData(List < Datum > data) {
this.data = data;
}
/**
*
* #return
* The code
*/
public Integer getCode() {
return code;
}
/**
*
* #param code
* The Code
*/
public void setCode(Integer code) {
this.code = code;
}
/**
*
* #return
* The message
*/
public Object getMessage() {
return message;
}
/**
*
* #param message
* The Message
*/
public void setMessage(Object message) {
this.message = message;
}
public Map < String,
Object > getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public class Datum implements Serializable {
#SerializedName("UserId")#Expose
private Integer userID;#SerializedName("FirstName")#Expose
private String firstName;#SerializedName("LastName")#Expose
private String lastName;#SerializedName("Title")#Expose
private String title;#SerializedName("Organization")#Expose
private String organization;#SerializedName("Industry")#Expose
private String industry;#SerializedName("Location")#Expose
private String location;#SerializedName("ProfileSummary")#Expose
private String profileSummary;#SerializedName("ImagePath")#Expose
private String imagePath;#SerializedName("Interests")#Expose
private ArrayList < Interest > interest = new ArrayList < Interest > ();
private Map < String,
Object > additionalProperties = new HashMap < String,
Object > ();
/**
*
* #return
* The userID
*/
public Integer getUserID() {
return userID;
}
/**
*
* #param userID
* The UserID
*/
public void setUserID(Integer userID) {
this.userID = userID;
}
/**
*
* #return
* The firstName
*/
public String getFirstName() {
return firstName;
}
/**
*
* #param firstName
* The FirstName
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
*
* #return
* The lastName
*/
public String getLastName() {
return lastName;
}
/**
*
* #param lastName
* The LastName
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The Title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The organization
*/
public String getOrganization() {
return organization;
}
/**
*
* #param organization
* The Organization
*/
public void setOrganization(String organization) {
this.organization = organization;
}
/**
*
* #return
* The industry
*/
public String getIndustry() {
return industry;
}
/**
*
* #param industry
* The Industry
*/
public void setIndustry(String industry) {
this.industry = industry;
}
/**
*
* #return
* The location
*/
public String getLocation() {
return location;
}
/**
*
* #param location
* The Location
*/
public void setLocation(String location) {
this.location = location;
}
/**
*
* #return
* The profileSummary
*/
public String getProfileSummary() {
return profileSummary;
}
/**
*
* #param profileSummary
* The ProfileSummary
*/
public void setProfileSummary(String profileSummary) {
this.profileSummary = profileSummary;
}
/**
*
* #return
* The imagePath
*/
public String getImagePath() {
return imagePath;
}
/**
*
* #param imagePath
* The ImagePath
*/
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
/**
*
* #return
* The interests
*/
public ArrayList < Interest > getInterest() {
return interest;
}
/**
*
* #param interests
* The Interests
*/
public void setInterest(ArrayList < Interest > interests) {
this.interest = interests;
}
public Map < String,
Object > getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
public class Interest {
#SerializedName("Name")#Expose
private String name;
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The Name
*/
public void setName(String name) {
this.name = name;
}
}
}
May be because the objects were not properly serialized so GSON was unable to parse the JSON String properly.
Others advice over the above assumption is most welcome.

passing custom object in retrofit2

i am trying to pass a custom object via retrofit2, and my question is that does the server writes my custom object to json automatically or do i have to write a php file for that. In the meanwhile I am posting successfully to the server but unable to write to json.
My aim is to write custom object to server, and write the contents of custom objects to json file.
Here is my Retrofit Api
public interface ApsaraCatalogAPI {
#GET("/apsaratrendz/data/apsara_json_document_v2.json")
Call<List<ApsaraCatalogModel>> getFeed();
#POST("/apsaratrendz/data/apsara_json_orders_document.json")
Call<Void> setOrder(#Body OrderModel orderModel);
}
Here is my calling api function
#Override
public void onClick(View v) {
int total = 0;
if(v.getId()==R.id.fabButtonCart && cartlist.size()!=0)
{
// get details from shared preferences
OrderModel orderModel = new OrderModel();
orderModel.setDate(getDate());
orderModel.setName("ssdfs");
orderModel.setEmail("sdf#gmail.com");
orderModel.setNoofitems(String.valueOf(cartlist.size()));
orderModel.setOrderno("32335");
orderModel.setPhone("9896566444");
for(int i=0; i<cartlist.size();i++){
Productdetail pd = new Productdetail();
pd.getSellingprice(String.valueOf(cartlist.get(i).getSellingPrice()));
pd.getPid(cartlist.get(i).getEANCode());
total += cartlist.get(i).getSellingPrice();
orderModel.getProductdetails().add(pd);
}
//
// now go for insertion using retrofit
requestData(orderModel);
Toast.makeText(getApplicationContext(), "Total Price : Rs."+total+"/-", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Cart is Empty", Toast.LENGTH_LONG).show();
}
}
And here is my service request for retrofit api, I am passing the newly created POJO OrderModel class.
private void requestData(OrderModel orderModel) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApsaraCatalogAPI service = retrofit.create(ApsaraCatalogAPI.class);
Call<Void> call = service.setOrder(orderModel);
call.enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
if(response.isSuccessful()){
Log.d("InApi","Yipppie");
}
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
Log.d("InApi","Kaboom");
}
});
}
My POJO Class is given below:
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class OrderModel {
private String name;
private String email;
private String phone;
private String orderno;
private String date;
private String noofitems;
private List<Productdetail> productdetails = new ArrayList<Productdetail>();
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The email
*/
public String getEmail() {
return email;
}
/**
*
* #param email
* The email
*/
public void setEmail(String email) {
this.email = email;
}
/**
*
* #return
* The phone
*/
public String getPhone() {
return phone;
}
/**
*
* #param phone
* The phone
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
*
* #return
* The orderno
*/
public String getOrderno() {
return orderno;
}
/**
*
* #param orderno
* The orderno
*/
public void setOrderno(String orderno) {
this.orderno = orderno;
}
/**
*
* #return
* The date
*/
public String getDate() {
return date;
}
/**
*
* #param date
* The date
*/
public void setDate(String date) {
this.date = date;
}
/**
*
* #return
* The noofitems
*/
public String getNoofitems() {
return noofitems;
}
/**
*
* #param noofitems
* The noofitems
*/
public void setNoofitems(String noofitems) {
this.noofitems = noofitems;
}
/**
*
* #return
* The productdetails
*/
public List<Productdetail> getProductdetails() {
return productdetails;
}
/**
*
* #param productdetails
* The productdetails
*/
public void setProductdetails(List<Productdetail> productdetails) {
this.productdetails = productdetails;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
productdetails class :
import java.util.HashMap;
import java.util.Map;
public class Productdetail {
private String pid;
private String sellingprice;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The pid
* #param s
*/
public String getPid(String s) {
return pid;
}
/**
*
* #param pid
* The pid
*/
public void setPid(String pid) {
this.pid = pid;
}
/**
*
* #return
* The sellingprice
* #param s
*/
public String getSellingprice(String s) {
return sellingprice;
}
/**
*
* #param sellingprice
* The sellingprice
*/
public void setSellingprice(String sellingprice) {
this.sellingprice = sellingprice;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Retrofit generates the json based on your POJO and set it on the post payload.
So, in this case:
#POST("/apsaratrendz/data/apsara_json_orders_document.json")
Call<Void> setOrder(#Body OrderModel orderModel);
the body of the post will be a json representation of orderModel.
If you need to change the names of the atributtes generated in the json you can use SerializedName Annotation, its very useful:
public class OrderModel {
#SerializedName("other_name_for_json")
private String name;
Hope it helps.

Parsing json to pojo, which consist of lists, Using GSON

I've got a problem when I try to parse a json string into my custom class, which consists of a list of another pojo.
the error I get is:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 226
And the class I try to parse is:
package com.example.client.models;
import java.util.List;
public class Catalog {
private List<Artist> list;
public Catalog() { }
/**
* #param list
*/
public Catalog(List<Artist> list) {
super();
this.list = list;
}
/**
* #return the list
*/
public List<Artist> getList() {
return list;
}
/**
* #param list the list to set
*/
public void setList(List<Artist> list) {
this.list = list;
}
}
And the artist class:
package com.example.client.models;
import java.io.File;
import java.util.List;
public class Artist {
private String artistName;
private List<Album> albumList;
private File artistFile;
public Artist() { }
/**
* #param artistName
* #param albumList
* #param artistFile
*/
public Artist(String artistName, List<Album> albumList, File artistFile) {
super();
this.artistName = artistName;
this.albumList = albumList;
this.artistFile = artistFile;
}
/**
* #return the artistName
*/
public String getArtistName() {
return artistName;
}
/**
* #param artistName the artistName to set
*/
public void setArtistName(String artistName) {
this.artistName = artistName;
}
/**
* #return the albumList
*/
public List<Album> getAlbumList() {
return albumList;
}
/**
* #param albumList the albumList to set
*/
public void setAlbumList(List<Album> albumList) {
this.albumList = albumList;
}
/**
* #return the artistFile
*/
public File getArtistFile() {
return artistFile;
}
/**
* #param artistFile the artistFile to set
*/
public void setArtistFile(File artistFile) {
this.artistFile = artistFile;
}
}
The Album class:
package com.example.client.models;
import java.io.File;
import java.util.List;
public class Album {
private String albumName;
private List<Song> songList;
private File albumFile;
public Album() { }
/**
* #param albumName
* #param songList
* #param albumFile
*/
public Album(String albumName, List<Song> songList, File albumFile) {
super();
this.albumName = albumName;
this.songList = songList;
this.albumFile = albumFile;
}
/**
* #return the albumName
*/
public String getAlbumName() {
return albumName;
}
/**
* #param albumName the albumName to set
*/
public void setAlbumName(String albumName) {
this.albumName = albumName;
}
/**
* #return the songList
*/
public List<Song> getSongList() {
return songList;
}
/**
* #param songList the songList to set
*/
public void setSongList(List<Song> songList) {
this.songList = songList;
}
/**
* #return the albumFile
*/
public File getAlbumFile() {
return albumFile;
}
/**
* #param albumFile the albumFile to set
*/
public void setAlbumFile(File albumFile) {
this.albumFile = albumFile;
}
}
and finally the song class:
package com.example.client.models;
import java.io.File;
public class Song {
private String songName;
private File songFile;
public Song() { }
/**
* #param songName
* #param songFile
*/
public Song(String songName, File songFile) {
super();
this.songName = songName;
this.songFile = songFile;
}
/**
* #return the songName
*/
public String getSongName() {
return songName;
}
/**
* #param songName the songName to set
*/
public void setSongName(String songName) {
this.songName = songName;
}
/**
* #return the songFile
*/
public File getSongFile() {
return songFile;
}
/**
* #param songFile the songFile to set
*/
public void setSongFile(File songFile) {
this.songFile = songFile;
}
}
I already have validated the json string, therefore I guess my problem lays in the GSON parsing. I hope you can help me with my problem
It would be nice if you could give an example or a hint of what to do.
Thanks on beforehand! ;)
EDIT
Hey again
I've included a sample of the JSON string i'm using:
{
"list":[
{
"artistName":"tmpArtistName",
"albumList":[
{
"albumName":"tmpAlbumName",
"songList":[
{
"songName":"tmpSongName",
"songFile":"/home/pi/tmpSongFile"
},
{
"songName":"tmpSongName",
"songFile":"/home/pi/tmpSongFile"
}
],
"albumFile":"/home/pi/tmpAlbumFile"
},
{
"albumName":"tmpAlbumName",
"songList":[
{
"songName":"tmpSongName",
"songFile":"/home/pi/tmpSongFile"
},
{
"songName":"tmpSongName",
"songFile":"/home/pi/tmpSongFile"
}
],
"albumFile":"/home/pi/tmpAlbumFile"
}
],
"artistFile":"/home/pi/tmpArtistFile"
},
{
"artistName":"tmpArtistName",
"albumList":[
{
"albumName":"tmpAlbumName",
"songList":[
{
"songName":"tmpSongName",
"songFile":"/home/pi/tmpSongFile"
},
{
"songName":"tmpSongName",
"songFile":"/home/pi/tmpSongFile"
}
],
"albumFile":"/home/pi/tmpAlbumFile"
},
{
"albumName":"tmpAlbumName",
"songList":[
{
"songName":"tmpSongName",
"songFile":"/home/pi/tmpSongFile"
},
{
"songName":"tmpSongName",
"songFile":"/home/pi/tmpSongFile"
}
],
"albumFile":"/home/pi/tmpAlbumFile"
}
],
"artistFile":"/home/pi/tmpArtistFile"
}
]
}
The Gson parser is apparently unable to deserialize strings directly into File objects. Instead it expects a matching JSON object (surrounded by { and }) in order to proceed with the unmarshalling. In order to get around this, you can simply register a type adapter to handle the file attributes:
public class FileTypeAdapter extends TypeAdapter<File> {
#Override
public void write(final JsonWriter out, final File value)
throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(value.getAbsolutePath());
}
}
#Override
public File read(final JsonReader in) throws IOException {
if (in.hasNext()) {
final String name = in.nextString();
return name != null ? new File(name) : null;
}
return null;
}
}
To use this, the rest of your code would remain the same, but replace the creation of your Gson parser:
final Gson gson = new Gson();
With this:
final Gson gson = new GsonBuilder().registerTypeAdapter(File.class,
new FileTypeAdapter()).create();
That should fix the issue.
On a side note, the Jackson library can handle these kind of deserializations with no special customization, if you are inclined and able to switch.

Categories