I'm new to JAXB and have troubles with conversion from XML to a Java class instance.
I have the following XML:
<?xml version="1.0"?>
<response>
<category>client</category>
<action>Greeting</action>
<code>1000</code>
<msg>Your Connection with API Server is Successful</msg>
<resData>
<data name="svDate">2009-02-16 06:22:21</data>
</resData>
</response>
and I develop the following Java code:
/**
* Copyright 2013. ABN Software. All Rights reserved.<br>
* Author ...... Andre<br>
* Created ..... 14.03.2013<br>
* <br>
*/
package net.regmaster.onlinenic.model;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import net.regmaster.onlinenic.enumtype.OnicEnumAction;
import net.regmaster.onlinenic.enumtype.OnicEnumCategory;
import net.regmaster.onlinenic.model.resdata.GreetingResData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* #author annik
*
*/
#XmlRootElement(name = "response")
// #XmlType( propOrder = { "category", "action", "code", "message"})
public class OnicGreeting
{
private OnicEnumCategory category;
private OnicEnumAction action;
private Integer code;
private String message;
private GreetingResData resData;
//
private Logger LOG = LoggerFactory.getLogger(getClass());
/**
* Getter.
*
* #return the category
*/
public OnicEnumCategory getCategory() {
return category;
}
/**
* Setter.
*
* #param category
* the category to set
*/
public void setCategoryEnum(OnicEnumCategory category) {
this.category = category;
}
#XmlElement
public void setCategory(String category) {
try {
this.category = OnicEnumCategory.getEnum(category);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error(e.getMessage());
}
}
/**
* Getter.
*
* #return the action
*/
public OnicEnumAction getAction() {
return action;
}
/**
* Setter.
*
* #param action
* the action to set
*/
public void setActionEnum(OnicEnumAction action) {
this.action = action;
}
#XmlElement
public void setAction(String action) {
try {
this.action = OnicEnumAction.getEnum(action);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error(e.getMessage());
}
}
/**
* Getter.
*
* #return the code
*/
#XmlElement
public Integer getCode() {
return code;
}
/**
* Setter.
*
* #param code
* the code to set
*/
public void setCode(Integer code) {
this.code = code;
}
/**
* Getter.
*
* #return the message
*/
#XmlElement(name = "msg")
public String getMessage() {
return message;
}
/**
* Setter.
*
* #param message
* the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Getter.
*
* #return the resData
*/
#XmlElementRef
public GreetingResData getResData() {
return resData;
}
/**
* Setter.
*
* #param resData
* the resData to set
*/
public void setResData(GreetingResData resData) {
this.resData = resData;
}
#Override
public String toString() {
return "category=" + category + ", action=" + action + ", code=" + code + ", msg=" + message
+ ", resData:" + resData.toString();
}
}
and
/**
* Copyright 2013. ABN Software. All Rights reserved.<br>
* Author ...... Andre<br>
* Created ..... 14.03.2013<br>
* <br>
*/
package net.regmaster.onlinenic.model.resdata;
import java.util.Calendar;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* #author annik
*
*/
#XmlRootElement(name="resData")
public class GreetingResData extends AbstractResData
{
String svDate;
/**
* Constructor.
*
*/
public GreetingResData() {
// TODO Auto-generated constructor stub
}
/**
* Getter.
*
* #return the svDate
*/
#XmlAttribute
public String getSvDate() {
return svDate;
}
/**
* Setter.
*
* #param svDate
* the svDate to set
*/
public void setSvDate(String svDate) {
this.svDate = svDate;
}
}
These code examples run but data is wrong :
http://i.stack.imgur.com/qCCIM.png
Please help me.
Also I do not understand in case I will have many different
<data ...>..</data>
What could I do easy and simply?
I mean this case:
<resData>
<data name="crDate">2004-12-17</data>
<data name="exDate">2009-01-02</data>
<data name="password">7fe11fd9d97ee40bdf57e561427c0a6</data>
<data name="dns">dns1.onlinenic.net</data>
<data name="dns">dns2.onlinenic.net</data>
<data name="r_name">123456</data>
<data name="r_org">123456</data>
<data name="r_country">BJ</data>
<data name="r_province">mokcup</data>
<data name="r_city">123456</data>
<data name="r_street">123456</data>
<data name="r_postalcode">123456</data>
<data name="r_voice">+86.5925391800</data>
<data name="r_fax">+86.5925391800</data>
<data name="r_email">asdfasdf#sadf.com</data>
....
Thank you Blaise Doughan.
But after dug more over 10 topics I decide I HAD TO to start with opposite way.
I created new test which MARSHALLING my data (objects). Actually, I used TDD (test Driven Development) way I think.
So, I filled up my Objects with test data and applied Marshalling (created XML from DATA) and saw that I got. Data Was Incorrect. I looked to other topic also (thanx this one Java/JAXB: Unmarshall Xml to specific subclass based on an attribute ) and correct my data Structure
remember Id like to get
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
<code>1000</code>
<message>Big message</message>
<resData>
<data name="svDate">2013.03.14</data>
</resData>
</response>
Now my data are :
package net.regmaster.onlinenic.model.response.resdata;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import org.eclipse.persistence.oxm.annotations.XmlCustomizer;
/**
* #author annik
*
*/
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name="data")
//#XmlCustomizer(ResDataCustomiser.class)
public class XmlData
{
#XmlAttribute(name="name")
private String name;
#XmlValue
private String value;
/** Getter.
* #return the name
*/
public String getName() {
return name;
}
/** Setter.
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/** Getter.
* #return the value
*/
public String getValue() {
return value;
}
/** Setter.
* #param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
}
and :
package net.regmaster.onlinenic.model.response.resdata;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
/**
* #author annik
*
*/
#XmlRootElement
public class ResData
{
private List<XmlData> data;
/**
* Getter.
*
* #return the data
*/
public List<XmlData> getData() {
return data;
}
/**
* Setter.
*
* #param data
* the data to set
*/
public void setData(List<XmlData> data) {
this.data = data;
}
}
and :
package net.regmaster.onlinenic.model.response;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import net.regmaster.onlinenic.enumtype.OnicEnumAction;
import net.regmaster.onlinenic.enumtype.OnicEnumCategory;
import net.regmaster.onlinenic.model.response.resdata.ResData;
import net.regmaster.onlinenic.model.response.resdata.XmlData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* #author annik
*
*/
#XmlRootElement(name = "response")
//#XmlType( propOrder = { "category", "action", "code", "message"})
public class OnicGreetingResponse
{
private OnicEnumCategory category;
private OnicEnumAction action;
private Integer code;
private String message;
// private GreetingResData resData;
private ResData resData;
//
#XmlTransient
private Logger LOG = LoggerFactory.getLogger(getClass());
/**
* Getter.
*
* #return the category
*/
public OnicEnumCategory getCategory() {
return category;
}
/**
* Setter.
*
* #param category
* the category to set
*/
public void setCategoryEnum(OnicEnumCategory category) {
this.category = category;
}
#XmlElement
public void setCategory(String category) {
try {
this.category = OnicEnumCategory.getEnum(category);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error(e.getMessage());
}
}
/**
* Getter.
*
* #return the action
*/
public OnicEnumAction getAction() {
return action;
}
/**
* Setter.
*
* #param action
* the action to set
*/
public void setActionEnum(OnicEnumAction action) {
this.action = action;
}
#XmlElement
public void setAction(String action) {
try {
this.action = OnicEnumAction.getEnum(action);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error(e.getMessage());
}
}
/**
* Getter.
*
* #return the code
*/
#XmlElement
public Integer getCode() {
return code;
}
/**
* Setter.
*
* #param code
* the code to set
*/
public void setCode(Integer code) {
this.code = code;
}
/**
* Getter.
*
* #return the message
*/
#XmlElements(value={#XmlElement})
public String getMessage() {
return message;
}
/**
* Setter.
*
* #param message
* the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/** Getter.
* #return the resData
*/
public ResData getResData() {
return resData;
}
/** Setter.
* #param resData the resData to set
*/
#XmlElement
public void setResData(ResData resData) {
this.resData = resData;
}
#Override
public String toString() {
return "category=" + category + ", action=" + action + ", code=" + code + ", msg=" + message
+ ", resData:" + resData.toString();
}
}
and vu-alja :
I got that !
And as you can see below it works to another way :
http://i.stack.imgur.com/35nzb.png
Related
Having hard time to map..
Calling rest and rest return response in XML format..
Help with class mapping in Java Object (method)
<aname>
<bname>
<c id="2">
<cname call="yes" text="no" email="yes"/>
<acc>
<accinfo name="ax" addr="USA"/>
</acc>
</c>
</bname>
</aname>
how can i convert above xml in Java class?
Thank You!
I share solution:
If you use need dependency
<!-- Jaxb -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
First class.
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "bname" })
#XmlRootElement(name = "aname")
public class Aname {
#XmlElement(required = true)
protected Aname.Bname bname;
/**
* Gets the value of the bname property.
*
* #return possible object is {#link Aname.Bname }
*
*/
public Aname.Bname getBname() {
return bname;
}
/**
* Sets the value of the bname property.
*
* #param value allowed object is {#link Aname.Bname }
*
*/
public void setBname(Aname.Bname value) {
this.bname = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "c" })
public static class Bname {
#XmlElement(required = true)
protected Aname.Bname.C c;
/**
* Gets the value of the c property.
*
* #return possible object is {#link Aname.Bname.C }
*
*/
public Aname.Bname.C getC() {
return c;
}
/**
* Sets the value of the c property.
*
* #param value allowed object is {#link Aname.Bname.C }
*
*/
public void setC(Aname.Bname.C value) {
this.c = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "cname", "acc" })
public static class C {
#XmlElement(required = true)
protected Aname.Bname.C.Cname cname;
#XmlElement(required = true)
protected Aname.Bname.C.Acc acc;
#XmlAttribute(name = "id", required = true)
#XmlSchemaType(name = "unsignedByte")
protected short id;
/**
* Gets the value of the cname property.
*
* #return possible object is {#link Aname.Bname.C.Cname }
*
*/
public Aname.Bname.C.Cname getCname() {
return cname;
}
/**
* Sets the value of the cname property.
*
* #param value allowed object is {#link Aname.Bname.C.Cname }
*
*/
public void setCname(Aname.Bname.C.Cname value) {
this.cname = value;
}
/**
* Gets the value of the acc property.
*
* #return possible object is {#link Aname.Bname.C.Acc }
*
*/
public Aname.Bname.C.Acc getAcc() {
return acc;
}
/**
* Sets the value of the acc property.
*
* #param value allowed object is {#link Aname.Bname.C.Acc }
*
*/
public void setAcc(Aname.Bname.C.Acc value) {
this.acc = value;
}
/**
* Gets the value of the id property.
*
*/
public short getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(short value) {
this.id = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "accinfo" })
public static class Acc {
#XmlElement(required = true)
protected Aname.Bname.C.Acc.Accinfo accinfo;
/**
* Gets the value of the accinfo property.
*
* #return possible object is {#link Aname.Bname.C.Acc.Accinfo }
*
*/
public Aname.Bname.C.Acc.Accinfo getAccinfo() {
return accinfo;
}
/**
* Sets the value of the accinfo property.
*
* #param value allowed object is {#link Aname.Bname.C.Acc.Accinfo }
*
*/
public void setAccinfo(Aname.Bname.C.Acc.Accinfo value) {
this.accinfo = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "")
public static class Accinfo {
#XmlAttribute(name = "name", required = true)
protected String name;
#XmlAttribute(name = "addr", required = true)
protected String addr;
/**
* Gets the value of the name property.
*
* #return possible object is {#link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* #param value allowed object is {#link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the addr property.
*
* #return possible object is {#link String }
*
*/
public String getAddr() {
return addr;
}
/**
* Sets the value of the addr property.
*
* #param value allowed object is {#link String }
*
*/
public void setAddr(String value) {
this.addr = value;
}
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "")
public static class Cname {
#XmlAttribute(name = "call", required = true)
protected String call;
#XmlAttribute(name = "text", required = true)
protected String text;
#XmlAttribute(name = "email", required = true)
protected String email;
/**
* Gets the value of the call property.
*
* #return possible object is {#link String }
*
*/
public String getCall() {
return call;
}
/**
* Sets the value of the call property.
*
* #param value allowed object is {#link String }
*
*/
public void setCall(String value) {
this.call = value;
}
/**
* Gets the value of the text property.
*
* #return possible object is {#link String }
*
*/
public String getText() {
return text;
}
/**
* Sets the value of the text property.
*
* #param value allowed object is {#link String }
*
*/
public void setText(String value) {
this.text = value;
}
/**
* Gets the value of the email property.
*
* #return possible object is {#link String }
*
*/
public String getEmail() {
return email;
}
/**
* Sets the value of the email property.
*
* #param value allowed object is {#link String }
*
*/
public void setEmail(String value) {
this.email = value;
}
}
}
}
}
Second class.
import javax.xml.bind.annotation.XmlRegistry;
#XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema
* derived classes for package: generated
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {#link Aname }
*
*/
public Aname createAname() {
return new Aname();
}
/**
* Create an instance of {#link Aname.Bname }
*
*/
public Aname.Bname createAnameBname() {
return new Aname.Bname();
}
/**
* Create an instance of {#link Aname.Bname.C }
*
*/
public Aname.Bname.C createAnameBnameC() {
return new Aname.Bname.C();
}
/**
* Create an instance of {#link Aname.Bname.C.Acc }
*
*/
public Aname.Bname.C.Acc createAnameBnameCAcc() {
return new Aname.Bname.C.Acc();
}
/**
* Create an instance of {#link Aname.Bname.C.Cname }
*
*/
public Aname.Bname.C.Cname createAnameBnameCCname() {
return new Aname.Bname.C.Cname();
}
/**
* Create an instance of {#link Aname.Bname.C.Acc.Accinfo }
*
*/
public Aname.Bname.C.Acc.Accinfo createAnameBnameCAccAccinfo() {
return new Aname.Bname.C.Acc.Accinfo();
}
}
And Main class.
import java.io.StringReader;
import java.text.ParseException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
static ObjectMapper mapper = new ObjectMapper();
public static void main(String... strings) throws ParseException {
String xml = "<aname> <bname> <c id=\"2\"> <cname call=\"yes\" text=\"no\" email=\"yes\"/> <acc> <accinfo name=\"ax\" addr=\"USA\"/> </acc> </c> </bname> </aname>";
Aname clazz = convertXMLToObject(Aname.class, xml);
try {
System.out.println(mapper.writeValueAsString(clazz));
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
public static <T> T convertXMLToObject(Class<T> clazz, String xml)
{
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller um = context.createUnmarshaller();
return (T) um.unmarshal(new StringReader(xml));
}
catch (JAXBException je){
throw new RuntimeException(String.format("Exception while Unmarshaller: %s", je.getMessage()));
}
}
}
result this.
{"bname":{"c":{"cname":{"call":"yes","text":"no","email":"yes"},"acc":{"accinfo":{"name":"ax","addr":"USA"}},"id":2}}}
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;
}
}
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.
I just started with rest services and i have read this https://spring.io/guides/gs/consuming-rest/. Then according to this tutorial i have a service to consume and display.
The service is a rest api and i get a json like that
{
"disclaimer": "1",
"license": "2",
"timestamp": 1458057661,
"base": "someValue",
"rates": {
"one": 3.673019,
"two": 68.449999,
"three": 124.168,
"four": 488.669996,
...,
...,
...
}
}
Then i have created 2 Java class like that
#JsonIgnoreProperties(ignoreUnknown = true)
public class Cur {
private String disclaimer;
private String license;
private String timestamp;
private String base;
private Rates rates;
public Cur() {
super();
}
///get/set
///tostring
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class Rates {
public Rates(){
//// i am not sure here how should i get the rates value.
}
}
the problem is how do i fill the Rates class to get the data into variables so that later i can present the on view.
I use RestTemplate. Here is the test.It works but i have no rates value.
I think i need a Map because rates it's a collection.Any idea how to implement it.
#Test
public void getCurTest() {
String URL="some url";
String JSONTYPE="some json type";
String API="some id";
RestTemplate restTemplate = new RestTemplate();
Cur cur= restTemplate.getForObject(URL+JSONTYPE+API, Cur.class);
log.info("cur");
System.out.println(cur);
}
I had the same some years ago it's a little weird. Here what you can do.
First solution
The simple way is
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("your rest service api");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
String responseValue = EntityUtils.toString(entity);
System.out.println(responseValue);
} else {
// log error
}
} finally {
response.close();
}
}
you can then get everything as a String and with regex parse it and get what you want.
Second solution
you can save all your rest to a database as it is. Use mongodb for faster.
Then you can get it form there to a class and use it.
Third solution
use this tool http://www.jsonschema2pojo.org/ just paste your json and it will create your java classes to use them. You can choose what ever you want to add. This will create your classes then you can use them.
Here for your convenience.
package com.example;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("org.jsonschema2pojo")
#JsonPropertyOrder({
"disclaimer",
"license",
"timestamp",
"base",
"rates"
})
public class Example {
#JsonProperty("disclaimer")
private String disclaimer;
#JsonProperty("license")
private String license;
#JsonProperty("timestamp")
private Integer timestamp;
#JsonProperty("base")
private String base;
#JsonProperty("rates")
private Rates rates;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public Example() {
}
/**
*
* #param timestamp
* #param disclaimer
* #param base
* #param rates
* #param license
*/
public Example(String disclaimer, String license, Integer timestamp, String base, Rates rates) {
this.disclaimer = disclaimer;
this.license = license;
this.timestamp = timestamp;
this.base = base;
this.rates = rates;
}
/**
*
* #return
* The disclaimer
*/
#JsonProperty("disclaimer")
public String getDisclaimer() {
return disclaimer;
}
/**
*
* #param disclaimer
* The disclaimer
*/
#JsonProperty("disclaimer")
public void setDisclaimer(String disclaimer) {
this.disclaimer = disclaimer;
}
/**
*
* #return
* The license
*/
#JsonProperty("license")
public String getLicense() {
return license;
}
/**
*
* #param license
* The license
*/
#JsonProperty("license")
public void setLicense(String license) {
this.license = license;
}
/**
*
* #return
* The timestamp
*/
#JsonProperty("timestamp")
public Integer getTimestamp() {
return timestamp;
}
/**
*
* #param timestamp
* The timestamp
*/
#JsonProperty("timestamp")
public void setTimestamp(Integer timestamp) {
this.timestamp = timestamp;
}
/**
*
* #return
* The base
*/
#JsonProperty("base")
public String getBase() {
return base;
}
/**
*
* #param base
* The base
*/
#JsonProperty("base")
public void setBase(String base) {
this.base = base;
}
/**
*
* #return
* The rates
*/
#JsonProperty("rates")
public Rates getRates() {
return rates;
}
/**
*
* #param rates
* The rates
*/
#JsonProperty("rates")
public void setRates(Rates rates) {
this.rates = rates;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
package com.example;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("org.jsonschema2pojo")
#JsonPropertyOrder({
"one",
"two",
"three",
"four"
})
public class Rates {
#JsonProperty("one")
private Double one;
#JsonProperty("two")
private Double two;
#JsonProperty("three")
private Double three;
#JsonProperty("four")
private Double four;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public Rates() {
}
/**
*
* #param two
* #param one
* #param three
* #param four
*/
public Rates(Double one, Double two, Double three, Double four) {
this.one = one;
this.two = two;
this.three = three;
this.four = four;
}
/**
*
* #return
* The one
*/
#JsonProperty("one")
public Double getOne() {
return one;
}
/**
*
* #param one
* The one
*/
#JsonProperty("one")
public void setOne(Double one) {
this.one = one;
}
/**
*
* #return
* The two
*/
#JsonProperty("two")
public Double getTwo() {
return two;
}
/**
*
* #param two
* The two
*/
#JsonProperty("two")
public void setTwo(Double two) {
this.two = two;
}
/**
*
* #return
* The three
*/
#JsonProperty("three")
public Double getThree() {
return three;
}
/**
*
* #param three
* The three
*/
#JsonProperty("three")
public void setThree(Double three) {
this.three = three;
}
/**
*
* #return
* The four
*/
#JsonProperty("four")
public Double getFour() {
return four;
}
/**
*
* #param four
* The four
*/
#JsonProperty("four")
public void setFour(Double four) {
this.four = four;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Then you can use it as you want.
I hope all this helps. Take care.
The way your JSON is, to get the Rates populed your class should look like this.
public class Cur {
private String disclaimer;
private String license;
private Integer timestamp;
private String base;
private Rates rates;
}
public class Rates {
private Double one;
private Double two;
private Double three;
private Double four;
//This would be better but the JSON dosnt fit this
//private Map<String, Double> rates;
}
Which API are you triyng to use?
I have a logical problem to understand, how create a private set of inhabitant object. Here my two classes:
package main;
import java.util.Set;
/**
* #author
* #version 0.1
*
*/
public class City {
private String name;
/**
*HERE is my Problem*/
private Set<Inhabitants> Inhabitants {
}
/**
* standard cunstructor
*/
public City(String n, ) {
setName(n);
}
/**
* Search a particular name of inhabitant
* #return object of inhabitant
*/
static Set<Inhabitants> Search(){
return inhabitants;
}
/**
* Creates a inhabitant object and
* add to the set of inhabitants of the city
*
* #param name
* #param datebirth
* #param maritalStatus
* #
*/
public void Add(String name,String datebirth,String maritalStatus) {
}
/**
* Return all inhabitants objects of the city
* #return
*/
static Set<Inhabitants> ReturnAll(){
return inhabitants;
}
/**
* Return city name
* #return
*/
static Set<Inhabitants> ReturnCityName(){
return inhabitants;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the inhabitants
*/
public Set<Inhabitants> getInhabitants() {
return inhabitants;
}
/**
* #param inhabitants the inhabitants to set
*/
public void setInhabitants(Set<Inhabitants> inhabitants) {
this.inhabitants = inhabitants;
}
}
package main;
/**
* #version 0.1
*/
public class Inhabitants {
private String name;
private String datebirth;
private Boolean maritalStatus;
/**
* standard constructor
*/
public Inhabitants() {
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the datebirth
*/
public String getDatebirth() {
return datebirth;
}
/**
* #param datebirth the datebirth to set
*/
public void setDatebirth(String datebirth) {
this.datebirth = datebirth;
}
/**
* #return the maritalStatus
*/
public Boolean getMaritalStatus() {
return maritalStatus;
}
/**
* #param maritalStatus the maritalStatus to set
*/
public void setMaritalStatus(Boolean maritalStatus) {
this.maritalStatus = maritalStatus;
}
}
It sounds like a simple problem. You didn't need so much code:
package collections;
/**
* Person
* #author Michael
* #link https://stackoverflow.com/questions/30958832/java-how-create-a-set-of-object-with-two-classes
* #since 6/20/2015 5:06 PM
*/
public class Person {
private final String name;
public Person(String name) {
if (name == null || name.trim().length() == 0) throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
public String getName() {
return name;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return name.equals(person.name);
}
#Override
public int hashCode() {
return name.hashCode();
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Person{");
sb.append("name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
}
package collections;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* City
* #author Michael
* #link https://stackoverflow.com/questions/30958832/java-how-create-a-set-of-object-with-two-classes
* #since 6/20/2015 5:06 PM
*/
public class City {
private Set<Person> inhabitants;
public City(Collection<Person> inhabitants) {
this.inhabitants = (inhabitants == null) ? new HashSet<Person>() : new HashSet<Person>(inhabitants);
}
public void addInhabitant(Person p) {
if (p != null) {
this.inhabitants.add(p);
}
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("City{");
sb.append("inhabitants=").append(inhabitants);
sb.append('}');
return sb.toString();
}
}