Field attribute is coming as null while unmarshalling an xml file - jaxb

Hi I am trying to convert an xml file into Java Objects using JAXB and I am very new to java. I have created the pojo classes and added some annotations but I am not sure whether they are right? I have spent hours in google but couldn't find what is wrong.
This is my xml :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<question id="1">
<answers>
<answername>java is a programming language</answername>
<id>101</id>
<postedby>ravi</postedby>
</answers>
<answers>
<answername>java is a platform</answername>
<id>102</id>
<postedby>john</postedby>
</answers>
<questionname>What is java?</questionname>
<marks set=50>
<longAnswer set=45/>
<shortAnswer set=30/>
</marks>
</question>
Pojo classes:
#XmlRootElement(name="question")
public class Question {
private int id;
private String questionname;
private List<Answer> answers;
private List<Marks> marks;
public Question() {}
public Question(int id, String questionname, List<Answer> answers, List<Marks> marks) {
super();
this.id = id;
this.questionname = questionname;
this.answers = answers;
this.marks = marks;
}
#XmlElement(name="marks")
public List<Marks> getMarks() {
return marks;
}
public void setMarks(List<Marks> marks) {
this.marks = marks;
}
#XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement
public String getQuestionname() {
return questionname;
}
public void setQuestionname(String questionname) {
this.questionname = questionname;
}
#XmlElement
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers) {
this.answers = answers;
}
}
public class Answer {
private int id;
private String answername;
private String postedby;
public Answer() {}
public Answer(int id, String answername, String postedby) {
super();
this.id = id;
this.answername = answername;
this.postedby = postedby;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAnswername() {
return answername;
}
public void setAnswername(String answername) {
this.answername = answername;
}
public String getPostedby() {
return postedby;
}
public void setPostedby(String postedby) {
this.postedby = postedby;
}
}
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
public class Marks {
private LongAnswer longAnswer ;
private ShortAnswer shortAnswer;
private String set;
#XmlAttribute
public String getSet() {
return set;
}
public void setSet(String set) {
this.set = set;
}
#XmlElement(name="longAnswer")
public LongAnswer getLongAnswer() {
return longAnswer;
}
public void setLongAnswer(LongAnswer longAnswer) {
this.longAnswer = longAnswer;
}
#XmlElement(name="shortAnswer")
public ShortAnswer getShortAnswer() {
return shortAnswer;
}
public void setShortAnswer(ShortAnswer shortAnswer) {
this.shortAnswer = shortAnswer;
}
}
public class LongAnswer {
private String set;
public String getSet() {
return set;
}
public void setSet(String set) {
this.set = set;
}
public class ShortAnswer {
private String set;
public String getSet() {
return set;
}
public void setSet(String set) {
this.set = set;
}
}
Can anyone tell me how to annotate the 'marks' model class and how to set 'longAnswer' and 'shortAnswer' field. Because i am getting null values for them.

You should annotate your set properties with #XmlAttribute. Otherwise it looks quite fine.
What you could also do is create an XML Schema for you XML and compile it.

Related

issues with parcelable extension: getting unmarshalling unknown type code exception

long story short, I have one settlementItemeBase class as my father and two children. I want to make the father class parcelable so as extension happens, my two child classes be parcelable as well. I don't exactly know what I'm doing right or wrong. I searched little bit but nothing helped me.
here are my classes:
SettlementItemBase:
public class SettlementItemBase implements Parcelable{
public SettlementItemBase(){}
protected SettlementItemBase(Parcel in) {
}
public static final Creator<SettlementItemBase> CREATOR = new Creator<SettlementItemBase>() {
#Override
public SettlementItemBase createFromParcel(Parcel in) {
return new SettlementItemBase(in);
}
#Override
public SettlementItemBase[] newArray(int size) {
return new SettlementItemBase[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
}
first child class:
public class FirstClass extends SettlementItemBase {
private int id;
private int cardId;
private String cardNumber;
private String expDate;
private String currency;
private String url;
public FirstClass(){
id = 0;
cardId = 0;
cardNumber = "";
expDate = "";
currency = "";
url = "";
}
protected FirstClass(Parcel in) {
super(in);
id = in.readInt();
cardId = in.readInt();
cardNumber = in.readString();
expDate = in.readString();
currency = in.readString();
url = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(cardId);
dest.writeString(cardNumber);
dest.writeString(expDate);
dest.writeString(currency);
dest.writeString(url);
}
public int getId() {
return id;
}
public int getCardId() {
return cardId;
}
public String getCardNumber() {
return cardNumber;
}
public String getExpDate() {
return expDate;
}
public String getCurrency() {
return currency;
}
public String getUrl() {
return url;
}
}
second child class:
public class SecondClass extends SettlementItemBase{
private int id;
private String currency;
private String accountNumber;
private String ibanNumber;
public SecondClass(int id, String currency,
String accountNumber, String ibanNumber){
this.id = id;
this.currency = currency;
this.accountNumber = accountNumber;
this.ibanNumber = ibanNumber;
}
protected SecondClass(Parcel in){
super(in);
id = in.readInt();
currency = in.readString();
accountNumber = in.readString();
ibanNumber = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(currency);
dest.writeString(accountNumber);
dest.writeString(ibanNumber);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCurrency() {
return currency;
}
public String getAccountNumber() {
return accountNumber;
}
public String getIbanNumber() {
return ibanNumber;
}
}
I'm passing and getting an ArrayList of both child class' items with intent putParcelableArrayListExtra and getParcelableArrayListExtra methods and get the following error:
Parcel android.os.Parcel#2d0fde33: Unmarshalling unknown type code 3276849 at offset 172
any help would be appreciated 3>
well I'm posting this for those who may run into the same problem as me.
the problem was solved after adding the Creator statement to the child classes.
for one of the child classes it would be like:
public static final Creator<FirstClass> CREATOR = new Creator<FirstClass>() {
#Override
public FirstClass createFromParcel(Parcel in) {
return new FirstClass(in);
}
#Override
public FirstClass[] newArray(int size) {
return new FirstClass[size];
}
};
hope this helps. 3>

JaxB Marshaling in camel

I am new to Apache camel and Jax b concept in java.
I have a list of java objects in a camel queue. I want to Marshall it to an xml with Javs DSL(without using spring).
Could any one guide me to do that?
I have the following POJO class
public class MyPojo {
private int groupId;
private int memberId;
private String details;
public int getgroupId() {
return groupId;
}
public void setgroupId(int groupId) {
this.groupId = groupId;
}
public int getMemberId() {
return memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public String getdetails() {
return details;
}
public void setdetails(String details) {
this.details = details;
}}
following is my camel code for jaxb implementation
JaxbDataFormat jaxbMarshal = new JaxbDataFormat();
jaxbMarshal.setContextPath("com.test");
jaxbMarshal.setPartClass("com.test.MyPojo");
from("direct:javaObjects") //this direct having the list of MYPojo Objects
.marshal(jaxbMarshal)
.to("src/output");
I am getting below exception(I added maven dependency for jaxb in classpath)
Failed to create route route4 at: >>> Marshal[org.apache.camel.model.dataformat.JaxbDataFormat#3feb2dda] <<< in route: Route(route4)[[From[direct:javaObjects]] -> [Marshal[org.apa... because of Data format 'jaxb' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
I have created the jaxb.index file(new->File from eclipse). the content of the file should be annotation class name
In our case it should be
MyPojo
and its needs to be placed in context path. in our case it should be placed in
com.test location
and the annotated Pojo class is
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement
public class MyPojo {
#XmlElement
private int groupId;
#XmlElement
private int memberId;
#XmlElement
private String details;
public int getgroupId() {
return groupId;
}
public void setgroupId(int groupId) {
this.groupId = groupId;
}
public int getMemberId() {
return memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public String getdetails() {
return details;
}
public void setdetails(String details) {
this.details = details;
}}
You can use your pojo with some annotations:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name="MY-POJO")
#XmlType(propOrder = {"groupId", "memberId", "details"})
public class MyPojo {
#XmlElement(name = "groupId")
private int groupId;
#XmlElement(name = "memberId")
private int memberId;
#XmlElement(name = "details")
private String details;
public int getgroupId() {
return groupId;
}
public void setgroupId(int groupId) {
this.groupId = groupId;
}
public int getMemberId() {
return memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public String getdetails() {
return details;
}
public void setdetails(String details) {
this.details = details;
}}

JAVA/JAXB : Marshal/UnMarshal using attributes in the xml or class members

I have XML as follows
<request type="1">
<request-header/>
<request-details>
<!-- Some more tags -->
</request-details>
</request>
For mapping this XML I have class structure as follows :
public class Request1
{
private RequestDetail_1;
//other members
}
public class Request2
{
private RequestDetail_2;
//other members
}
public class RequestDetail_1
{
//members
}
public class RequestDetail_2
{
//Members
}
What I want to do is ... If attribute type is 1 then I need to create object of type Request_1 , if type is 2 then object type will be Request_2 and so on.
I have gone through this link for reference but still couldn't figure out a way to do this. I want to use pure JAXB and not MOXY or any other such frame works... :( .
Partial code :
#XmlJavaTypeAdapter(RequestAdaptor.class)
#XmlRootElement(name="request")
public class AuthRequest extends Request
{
private AuthRequestDetails requestDetails;
public RequestDetails getRequestDetails()
{
return requestDetails;
}
#Override
public void setRequestDetails(RequestDetails requestDetails)
{
this.requestDetails = (AuthRequestDetails)requestDetails;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class AuthRequestDetails extends RequestDetails
{
#XmlElement(name="user-name")
private String userName;
#XmlElement(name="password")
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlJavaTypeAdapter(RequestAdaptor.class)
public abstract class Request
{
#XmlAttribute
protected String type;
#XmlElement(name="request-header")
protected RequestHeader requestHeader;
public RequestHeader getRequestHeader()
{
return requestHeader;
}
public void setRequestHeader(RequestHeader requestHeader)
{
this.requestHeader = requestHeader;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public abstract void setRequestDetails(RequestDetails requestDetails);
public abstract RequestDetails getRequestDetails();
}
public class RequestAdaptor extends XmlAdapter<RequestDTO, Request>
{
#Override
public RequestDTO marshal(Request v) throws Exception
{
System.out.println("marshal");
RequestDTO lRequestDTO= new RequestDTO();
lRequestDTO.setRequestHeader(v.getRequestHeader());
lRequestDTO.setType(v.getType());
if(v.getType().equals("5"))
{
AuthRequest lRequest = (AuthRequest)v;
}
else
{
PingRequest lRequest = (PingRequest)v;
}
return lRequestDTO;
}
#Override
public Request unmarshal(RequestDTO v) throws Exception
{
System.out.println("unmarshal");
if(v.getType().equals("5"))
{
AuthRequest lRequest = new AuthRequest();
lRequest.setRequestHeader(v.getRequestHeader());
lRequest.setType(v.getType());
return lRequest;
}
else
{
PingRequest lRequest = new PingRequest();
lRequest.setRequestHeader(v.getRequestHeader());
lRequest.setType(v.getType());
return lRequest;
}
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class RequestDTO
{
#XmlAttribute
protected String type;
#XmlElement(name="request-header")
private RequestHeader requestHeader;
#XmlElement(name="request-details")
private RequestDetails requestDetails;
public RequestHeader getRequestHeader()
{
return requestHeader;
}
public void setRequestHeader(RequestHeader requestHeader)
{
this.requestHeader = requestHeader;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public RequestDetails getRequestDetails() {
return requestDetails;
}
public void setRequestDetails(RequestDetails requestDetails) {
this.requestDetails = requestDetails;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class RequestHeader
{
#XmlElement(name="name")
String Name;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
First thing is : Marshal and Unmarshal of Adaptor is not getting called. I am stuck at this point.
You can use a StAX XmlStreamReader to parse the XML. Then advance it to the root element. When it's at the root element event check the value of the type attribute. Use this value to determine which Class you should pass to the unmarshal method that takes a Class and XmlStreamReader to get the result you are looking for.

Jaxb #Attribute error read attribute

I have the code and xml and xml and cannot read the xml and believe that it is for the attribute. how can I read the attribute?
This is the code:
#XmlRootElement(name = "reimpresiones")
public class RePrint {
private Integer id;
private String document;
private String numberDocument;
private String extraction;
private String client;
private String groupExtraction;
private String route;
private String deliveryNote;
private String date;
private List<RePrint> reprintList;
public RePrint() {
}
#XmlAttribute(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#XmlElement(name = "client")
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
#XmlElement(name = "document")
public String getDocument() {
return document;
}
public void setDocument(String document) {
this.document = document;
}
#XmlElement(name = "numberDocument")
public String getNumberDocument() {
return numberDocument;
}
public void setNumberDocument(String numberDocument) {
this.numberDocument = numberDocument;
}
#XmlElement(name = "extraction")
public String getExtraction() {
return extraction;
}
public void setExtraction(String extraction) {
this.extraction = extraction;
}
#XmlElement(name = "groupExtraction")
public String getGroupExtraction() {
return groupExtraction;
}
public void setGroupExtraction(String groupExtraction) {
this.groupExtraction = groupExtraction;
}
#XmlElement(name = "route")
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
#XmlElement(name = "deliveryNote")
public String getDeliveryNote() {
return deliveryNote;
}
public void setDeliveryNote(String deliveryNote) {
this.deliveryNote = deliveryNote;
}
#XmlElement(name = "date")
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#XmlElement(name = "reimprension")
public List<RePrint> getReprintList() {
return reprintList;
}
public void setReprintList(List<RePrint> reprintList) {
this.reprintList = reprintList;
}
}
This is the xml where there is a list of elements. I want to read "id" but i cannot.
<reimpresiones>
<reimpresion id="10574691840591525620140557591784">
<document>MATRICULA</document>
<numdocument><![CDATA[M142849865 ]]></numdocument>
<groupExtraction>1849986</groupExtraction>
<extraction>919767</extraction>
<client>780</client>
<deliveryNote><![CDATA[3600445640/01 ]]></deliveryNote>
<route>BUY</route>
<date>2014-05-05-17.59.57.919200</date>
</reimpresion>
<reimpresion id="14081953280539172820140537251728">
<document>MATRICULA</document>
<numdocument><![CDATA[M142849864 ]]></numdocument>
<groupExtraction>1849986</groupExtraction>
<extraction>919767</extraction>
<client>780</client>
<deliveryNote><![CDATA[3600445640/01 ]]></deliveryNote>
<route>BUY</route>
<date>2014-05-05-17.25.37.427752</date>
</reimpresion>
</reimpresiones>
Thank you

jaxb XmlAdapter unmarshall an object from the same xml

take a look at this code :
#XmlRootElement
class Course {
private int id;
private String name;
public Course() {}
public Course(int id, String name) {
super();
this.id = id;
this.name = name;
}
#XmlAttribute(name = "id")
public int getId() {
return id;
}
#XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
class CourseAdapter extends XmlAdapter<Integer, Course>{
#Override
public Course unmarshal(Integer v) throws Exception {
// what to do hereeeeeeeeeeeeeeee????!!!!
// I want the Course with the id = v unmarshalled from
// the same xml I am unmarshalling at the moment
}
#Override
public Integer marshal(Course v) throws Exception {
return v.getId();
}
}
#XmlRootElement
class Offering {
private int id;
private Course course;
private int capacity;
public Offering() {}
public Offering(int id, Course course, int capacity) {
super();
this.id = id;
this.course = course;
this.capacity = capacity;
}
#XmlAttribute(name = "id")
public int getId() {
return id;
}
#XmlJavaTypeAdapter(CourseAdapter.class)
#XmlAttribute(name = "course")
public Course getCourse() {
return course;
}
#XmlAttribute(name = "capacity")
public int getCapacity() {
return capacity;
}
public void setId(int id) {
this.id = id;
}
public void setCourse(Course course) {
this.course = course;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
}
#XmlRootElement
class Department {
private String name;
private ArrayList<Course> courses;
private ArrayList<Offering> offerings;
public Department(){}
public Department(String name, ArrayList<Course> courses, ArrayList<Offering> offerings) {
super();
this.name = name;
this.courses = courses;
this.offerings = offerings;
}
#XmlAttribute(name = "name")
public String getName() {
return name;
}
#XmlElement
public ArrayList<Course> getCourses() {
return courses;
}
#XmlElement
public ArrayList<Offering> getOfferings() {
return offerings;
}
public void setName(String name) {
this.name = name;
}
public void setCourses(ArrayList<Course> courses) {
this.courses = courses;
}
public void setOfferings(ArrayList<Offering> offerings) {
this.offerings = offerings;
}
}
I have marshalled my Department and this is the result:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<department name="ece">
<courses id="1" name="farsi"/>
<courses id="2" name="dini"/>
<courses id="2" name="riazi"/>
<offerings capacity="10" course="1" id="1"/>
<offerings capacity="20" course="2" id="2"/>
</department>
the problem is I do not know how to unmarshal course with the id = v from this very xml which is being unmarshalled via "unmarshal" function of CourseAdapter .
You can use #XmlID/#XmlIDREF for this use case without requiring an XmlAdapter.
http://blog.bdoughan.com/2010/10/jaxb-and-shared-references-xmlid-and.html

Resources