JAXB Moxy Element inside Text Content - java

I have to un-/marshall the following snippet
<para sizeInfoId="sizeInfo2" styleId="mono">Franz jagt im komplett verwahrlosten <protectedText>Taxi</protectedText> quer durch Bayern.</para>
My Java Model looks like this
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
#XmlType(propOrder = { AcrossParagraph.XML_ID, AcrossParagraph.XML_STYLE_ID, AcrossParagraph.XML_SIZEINFO_ID, AcrossParagraph.XML_COMMENT, AcrossParagraph.XML_CONTENT })
#XmlRootElement(name = AcrossParagraph.XML_ROOT_TAG)
public class AcrossParagraph {
public static final String XML_ROOT_TAG = "para";
public static final String XML_ID = "id";
public static final String XML_STYLE_ID = "styleId";
public static final String XML_SIZEINFO_ID = "sizeInfoId";
public static final String XML_COMMENT = "comment";
public static final String XML_CONTENT = "content";
private String id;
private String styleId;
private String sizeInfoId;
private String comment;
private String content;
#XmlAttribute(name = AcrossParagraph.XML_ID)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#XmlAttribute(name = AcrossParagraph.XML_STYLE_ID)
public String getStyleId() {
return styleId;
}
public void setStyleId(String styleId) {
this.styleId = styleId;
}
#XmlTransient
public void setStyleId(AcrossStyle style) {
this.styleId = style.getId();
}
#XmlAttribute(name = AcrossParagraph.XML_SIZEINFO_ID)
public String getSizeInfoId() {
return sizeInfoId;
}
public void setSizeInfoId(String sizeInfoId) {
this.sizeInfoId = sizeInfoId;
}
#XmlTransient
public void setSizeInfoId(AcrossSize size) {
this.sizeInfoId = size.getId();
}
#XmlAttribute(name = AcrossParagraph.XML_COMMENT)
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
#XmlValue
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
Without the inner protectedText Tag everything is working, but I don't know how to map that inner element.
I have read something about XmlAnyElement Annotation but havn't found an example for mapping something like this.
Any ideas?
Best regards,
Pascal

create new class for protectedText element:
#XmlRootElement(name = "protectedText")
class ProtectedText implements Serializable{
#XmlValue
public String value;
}
now change content property in AcrossParagraph as below:
private List<Serializable> content;
#XmlElementRef(name = "protectedText", type = ProtectedText.class)
#XmlMixed
public List<Serializable> getContent(){
return content;
}
public void setContent(List<Serializable> content){
this.content = content;
}
when you unmarshal the content list contains mix of String and ProtectedText

Related

Specifying root and child nodes with JAXB

Staying within JAXB how would I refactor MyNote so that it conforms to:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Which is well formed but not valid, to my understanding. Current output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<MyNotes>
<Note>
<note>XY3Z1RGEO9W79LALCS</note>
<to>LJAY9RNMUGGENGNND9</to>
<from>GOVSHVZ3GJWC864L7X</from>
<heading>EX6LGVE5LGY4A6B9SK</heading>
<body>L95WYQNMEU1MFDRBG4</body>
</Note>
</MyNotes>
which is too flat, rather than nested as the example.
I believe this makes note the root element, with other elements being children nodes to note if I'm using correct terminology.
The MyNote class:
package net.bounceme.dur.jaxb.hello.world;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlType(propOrder = {"note", "to", "from", "heading", "body"})
#XmlRootElement(name = "note")
public class MyNote {
private String note;
private String to;
private String from;
private String heading;
private String body;
public String getNote() {
return note;
}
#XmlElement(name = "note")
public void setNote(String note) {
this.note = note;
}
public String getTo() {
return to;
}
#XmlElement(name = "to")
public void setTo(String to) {
this.to = to;
}
public String getFrom() {
return from;
}
#XmlElement(name = "from")
public void setFrom(String from) {
this.from = from;
}
public String getHeading() {
return heading;
}
#XmlElement(name = "heading")
public void setHeading(String heading) {
this.heading = heading;
}
public String getBody() {
return body;
}
#XmlElement(name = "body")
public void setBody(String body) {
this.body = body;
}
#Override
public String toString() {
return note + to + from + heading + body;
}
}
The MyNotes class:
package net.bounceme.dur.jaxb.hello.world;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "MyNotes")
public class MyNotes {
private static final Logger LOG = Logger.getLogger(MyNotes.class.getName());
private List<MyNote> myNotes = new ArrayList<>();
public MyNotes() {
}
public List<MyNote> getMyNotes() {
LOG.info(myNotes.toString());
return myNotes;
}
#XmlElement(name = "Note")
public void setMyNotes(List<MyNote> myNotes) {
LOG.info(myNotes.toString());
this.myNotes = myNotes;
}
public void add(MyNote myNote) {
LOG.info(myNote.toString());
myNotes.add(myNote);
}
#Override
public String toString() {
StringBuffer str = new StringBuffer();
for (MyNote note : this.myNotes) {
str.append(note.toString());
}
return str.toString();
}
}
exercising the MyNote and MyNotes classes:
public MyNotes unmarshallMyNotesFromFile(URI uri) throws Exception {
File file = new File(uri);
JAXBContext jaxbContext = JAXBContext.newInstance(MyNotes.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
MyNotes myNotes = (MyNotes) jaxbUnmarshaller.unmarshal(file);
return myNotes;
}
public void marshallMyNotesAndWriteToFile(MyNotes notes, URI uri) throws Exception {
JAXBContext jaxbContext = JAXBContext.newInstance(MyNotes.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(notes, new File(uri));
jaxbMarshaller.marshal(notes, System.out);
}
I'm looking to grab this xml through the web; first need to match the structure to the example.
You are very close. You need to change how you name your xmlElement for myNotes in MyNotes class. Also MyNote should not have a note field itself (according to your desired xml). Your edited classes would look like this (I also removed the logging statements for my convenience):
#XmlType(propOrder = { "to", "from", "heading", "body"})
#XmlRootElement(name = "note")
public class MyNote {
private String to;
private String from;
private String heading;
private String body;
public String getTo() {
return to;
}
#XmlElement(name = "to")
public void setTo(String to) {
this.to = to;
}
public String getFrom() {
return from;
}
#XmlElement(name = "from")
public void setFrom(String from) {
this.from = from;
}
public String getHeading() {
return heading;
}
#XmlElement(name = "heading")
public void setHeading(String heading) {
this.heading = heading;
}
public String getBody() {
return body;
}
#XmlElement(name = "body")
public void setBody(String body) {
this.body = body;
}
#Override
public String toString() {
return to + from + heading + body;
}
}
and MyNotes:
#XmlRootElement(name = "MyNotes")
public class MyNotes {
private List<MyNote> myNotes = new ArrayList<>();
public MyNotes() {
}
public List<MyNote> getMyNotes() {
return myNotes;
}
#XmlElement(name = "note")
public void setMyNotes(List<MyNote> myNotes) {
this.myNotes = myNotes;
}
public void add(MyNote myNote) {
myNotes.add(myNote);
}
#Override
public String toString() {
StringBuffer str = new StringBuffer();
for (MyNote note : this.myNotes) {
str.append(note.toString());
}
return str.toString();
}
}

Android simpleXML Element '[element Name]' is already used

I have tried to use other problems brought up on this website, but none of them relate to what I am doing.
I am trying to 'deserialize' soap xml using simpleXML for an Android application. I'm getting closer and closer to getting this, but I have hit a brick wall here.
When I run my code, I get the following error:
org.simpleframework.xml.core.PersistenceException: Element 'serviceOrderCT' is already used with #org.simpleframework.xml.Element(name=, type=void, data=false, required=true) on field 'serviceOrderCT' private serviceOrderCT GetServiceOrdersResult.serviceOrderCT at line 26
So, the problem seems to be with the 'GetServiceOrdersResult.java' class (code below), but I can't put my finger on what it is.
I have been at this for hours and have gotten nowhere.
Help to get passed this problem would be appreciated.
Thanks.
[EDIT: Here's the XML File]
<GetServiceOrdersResponse xmlns="http://tempuri.org/">
<GetServiceOrdersResult xmlns:a="http://schemas.datacontract.org/2004/07/MobileWebService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:serviceOrderCT>
<a:_bill_to_Customer_No_>xxxxx</a:_bill_to_Customer_No_>
<a:_bill_to_Name>xxxxxxx</a:_bill_to_Name>
<a:_customer_No_ i:nil="true" />
<a:_description />
<a:_fix_By_Date>xxxxxxxxxxxxx</a:_fix_By_Date>
<a:_fix_By_Time />
<a:_fixed_Date>xxxxxxxxxxxx</a:_fixed_Date>
<a:_fixed_Time>xxxxxxxxxxxxxx</a:_fixed_Time>
<a:_name>xxxxxxxxxxxxxxx</a:_name>
<a:_no_>xxxxxxxxxxxxxxxxxxx</a:_no_>
<a:_order_Date>xxxxxxxxxxxxxxx</a:_order_Date>
<a:_order_Time>xxxxxxxxxxxxx</a:_order_Time>
<a:_responded_Date>xxxxxxxxxxxxxxxxxx</a:_responded_Date>
<a:_responded_Time />
<a:_response_Date>xxxxxxxxxxxxxxxxxx</a:_response_Date>
<a:_response_Time>xxxxxxxxxxxxxxxxxxxx</a:_response_Time>
<a:_transaction_Status>xxxxxxxxxxxxxxx</a:_transaction_Status>
<a:_your_Reference />
</a:serviceOrderCT>
<a:serviceOrderCT>
a:_bill_to_Customer_No_>xxxxx</a:_bill_to_Customer_No_>
<a:_bill_to_Name>xxxxxxx</a:_bill_to_Name>
<a:_customer_No_ i:nil="true" />
<a:_description />
<a:_fix_By_Date>xxxxxxxxxxxxx</a:_fix_By_Date>
<a:_fix_By_Time />
<a:_fixed_Date>xxxxxxxxxxxx</a:_fixed_Date>
<a:_fixed_Time>xxxxxxxxxxxxxx</a:_fixed_Time>
<a:_name>xxxxxxxxxxxxxxx</a:_name>
<a:_no_>xxxxxxxxxxxxxxxxxxx</a:_no_>
<a:_order_Date>xxxxxxxxxxxxxxx</a:_order_Date>
<a:_order_Time>xxxxxxxxxxxxx</a:_order_Time>
<a:_responded_Date>xxxxxxxxxxxxxxxxxx</a:_responded_Date>
<a:_responded_Time />
<a:_response_Date>xxxxxxxxxxxxxxxxxx</a:_response_Date>
<a:_response_Time>xxxxxxxxxxxxxxxxxxxx</a:_response_Time>
<a:_transaction_Status>xxxxxxxxxxxxxxx</a:_transaction_Status>
<a:_your_Reference />
</a:serviceOrderCT>
</GetServiceOrdersResult>
</GetServiceOrdersResponse>
Envelope.java
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
#Root
public class Envelope {
#Element(name = "Body")
private Body body;
public Body getBody() {
return body;
}
}
Body.java
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import java.util.List;
public class Body {
#Element(name = "GetServiceOrdersResponse")
private GetServiceOrdersResponse getServiceOrdersResponse;
public GetServiceOrdersResponse getServiceOrdersResponse() {
return getServiceOrdersResponse;
}
}
GetServiceOrdersResponse.java
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Path;
public class GetServiceOrdersResponse {
#Element(name = "GetServiceOrdersResult")
private GetServiceOrdersResult getServiceOrdersResult;
public GetServiceOrdersResult getGetServiceOrdersResult() {
return getServiceOrdersResult;
}
}
GetServiceOrdersResult.java
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import java.util.List;
public class GetServiceOrdersResult {
#Element
private serviceOrderCT serviceOrderCT;
public serviceOrderCT getServiceOrderCT() {
return serviceOrderCT;
}
}
serviceOrderCT
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
public class serviceOrderCT {
#Element(name = "_bill_to_Customer_No_", required = false)
private String billToCustomerNo;
#Element(name = "_bill_to_Name", required = false)
private String billToName;
#Element(name = "_customer_No_", required = false)
private String customerNo;
#Element(name = "_description", required = false)
private String description;
#Element(name = "_fix_By_Date", required = false)
private String fixByDate;
#Element(name = "_fix_By_Time", required = false)
private String fixByTime;
#Element(name = "_fixed_Date", required = false)
private String fixedDate;
#Element(name = "_fixed_Time", required = false)
private String fixedTime;
#Element(name = "_name", required = false)
private String name;
#Element(name = "_no_", required = false)
private String no;
#Element(name = "_order_Date", required = false)
private String orderDate;
#Element(name = "_order_Time", required = false)
private String orderTime;
#Element(name = "_responded_Date", required = false)
private String respondedDate;
#Element(name = "_responded_Time", required = false)
private String respondedTime;
#Element(name = "_response_Date", required = false)
private String responseDate;
#Element(name = "_response_Time", required = false)
private String responseTime;
#Element(name = "_transaction_Status", required = false)
private String transactionStatus;
#Element(name = "_your_Reference", required = false)
private String yourReference;
public serviceOrderCT() {
}
public String getBillToCustomerNo() {
return billToCustomerNo;
}
public void setBillToCustomerNo(String billToCustomerNo) {
this.billToCustomerNo = billToCustomerNo;
}
public String getBillToName() {
return billToName;
}
public void setBillToName(String billToName) {
this.billToName = billToName;
}
public String getCustomerNo() {
return customerNo;
}
public void setCustomerNo(String customerNo) {
this.customerNo = customerNo;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFixByDate() {
return fixByDate;
}
public void setFixByDate(String fixByDate) {
this.fixByDate = fixByDate;
}
public String getFixByTime() {
return fixByTime;
}
public void setFixByTime(String fixByTime) {
this.fixByTime = fixByTime;
}
public String getFixedDate() {
return fixedDate;
}
public void setFixedDate(String fixedDate) {
this.fixedDate = fixedDate;
}
public String getFixedTime() {
return fixedTime;
}
public void setFixedTime(String fixedTime) {
this.fixedTime = fixedTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
}
public String getRespondedDate() {
return respondedDate;
}
public void setRespondedDate(String respondedDate) {
this.respondedDate = respondedDate;
}
public String getRespondedTime() {
return respondedTime;
}
public void setRespondedTime(String respondedTime) {
this.respondedTime = respondedTime;
}
public String getResponseDate() {
return responseDate;
}
public void setResponseDate(String responseDate) {
this.responseDate = responseDate;
}
public String getResponseTime() {
return responseTime;
}
public void setResponseTime(String responseTime) {
this.responseTime = responseTime;
}
public String getTransactionStatus() {
return transactionStatus;
}
public void setTransactionStatus(String transactionStatus) {
this.transactionStatus = transactionStatus;
}
public String getYourReference() {
return yourReference;
}
public void setYourReference(String yourReference) {
this.yourReference = yourReference;
}
}
Main.java
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import java.io.File;
public class Main {
public static void main(String[] args) {
try {
Serializer serializer = new Persister();
File result = new File("C:\\Users\\xxxxxxxx\\Documents\\file.xml");
Envelope example = serializer.read(Envelope.class, result);
System.out.println(example.getBody().getServiceOrdersResponse().getGetServiceOrdersResult().getServiceOrderCT().getBillToCustomerNo());
} catch (Exception e) {
e.printStackTrace();
}
}
}
So, I solve my problem, a day after asking for help, on my own Yet again.
You have to implement an ElementList, if you want to get all three serviceOrderCTs. It was only picking up one.
If I removed the other two, I would get something back.
Advice for anyone who reads this, stick with the official documentation. It will help you a lot. http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#list

Adding attribute to xml element within JAXB API

I am using JAXB API for mapping a Java object to XML. My Java class is
#XmlRootElement(name = "ad")
#XmlAccessorType(XmlAccessType.FIELD)
class Item {
#XmlElement(name = "id", nillable = false)
#XmlCDATA
private int id;
#XmlElement(name = "url", nillable = false)
#XmlCDATA
private String url;
public Item() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Output is like this :
<ad>
<id><![CDATA[ 104 ]]></id>
<url><![CDATA[www.google.com]]></url>
</ad>
I need to add an attribute to url element, for example :
<ad>
<id><![CDATA[ 104 ]]></id>
<url type="fr"><![CDATA[www.google.fr]]></url>
</ad>
I have tried many combinaisons using #XmlValue and #XmlAttribute ...
Your url variable should not be a String, but should be its own type. You should create a separate class for the url item, Url, and give it a String field, type, with an #XmlAttribute annotation.
For example,
#XmlRootElement(name = "ad")
#XmlAccessorType(XmlAccessType.FIELD)
class Item {
#XmlElement(name = "id")
private int id;
#XmlElement(name = "url")
private Url url;
public Item() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
// #XmlAttribute
public Url getUrl() {
return url;
}
public void setUrl(Url url) {
this.url = url;
}
}
#XmlRootElement(name = "url")
#XmlAccessorType(XmlAccessType.FIELD)
class Url {
#XmlValue
private String value;
#XmlAttribute(name = "type")
private String type;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Note that I don't have MOXY so I can't use or test your #XmlCDATA annotation.

Reading XML files from java

I am trying to read an XML file from java program. I am able to read its contents.I am posting the XML file from which i am reading contents.
<?xml version="1.0" encoding="UTF-8" ?>
<customer id="100">
<age>29</age>
<name>lucifer</name>
</customer>
i am able to write its contents through java program i am posting my code..
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
#XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
#XmlAttribute
public void setId(int id) {
this.id = id;
}
}
public class CheckClass {
public static void main(String[] args) {
try {
File file = new File("./file/NewFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer.age);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
But i have to read values from this XML file which i can not.This is my XML file
<?xml version="1.0" encoding="UTF-8"?>
<DBConfig ID="1" Name ="" DriverName="" HostName="localhost" PortName="" DBName="" ServiceName="" User="" PassWord="" sid="">
<TableConfig ID= "1" TableName="">
</TableConfig>
</DBConfig>
When i am trying to access this xml values through java class i am getting this error..
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
Class has two properties of the same name "DBName"
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.getDBName()
at com.gamma.DBConf
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.DBName
at com.gamma.DBConf
Class has two properties of the same name "sid"
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.getSid()
at com.gamma.DBConf
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.sid
at com.gamma.DBConf
at com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException$Builder.check(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(Unknown Source)
at com.sun.xml.internal.bind.v2.ContextFactory.createContext(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.find(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at com.gamma.ReadXML.main(ReadXML.java:22)
and this is my java classes
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class DBConf {
public String Name;
public String DriverName;
public String HostName;
public String PortName;
public String DBName;
public String ServiceName;
public String User;
public String PassWord;
public String sid;
public String getName() {
return Name;
}
#XmlElement
public void setName(String name) {
Name = name;
}
public String getDriverName() {
return DriverName;
}
#XmlElement
public void setDriverName(String driverName) {
DriverName = driverName;
}
public String getHostName() {
return HostName;
}
#XmlElement
public void setHostName(String hostName) {
HostName = hostName;
}
public String getPortName() {
return PortName;
}
#XmlElement
public void setPortName(String portName) {
PortName = portName;
}
public String getDBName() {
return DBName;
}
#XmlElement
public void setDBName(String dBName) {
DBName = dBName;
}
public String getServiceName() {
return ServiceName;
}
#XmlElement
public void setServiceName(String serviceName) {
ServiceName = serviceName;
}
public String getUser() {
return User;
}
#XmlElement
public void setUser(String user) {
User = user;
}
public String getPassWord() {
return PassWord;
}
#XmlElement
public void setPassWord(String passWord) {
PassWord = passWord;
}
public String getSid() {
return sid;
}
#XmlElement
public void setSid(String sid) {
this.sid = sid;
}
}
And this is the main class
public class ReadXML {
/**
* #param args
*/
public static void main(String[] args) {
try {
File file = new File("./file/dbconfig.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(DBConf.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
DBConf db = (DBConf) jaxbUnmarshaller.unmarshal(file);
System.out.println(db.HostName);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
can anyone help
Note that you are annotating Attribute as Element. Fix that.
Even after that if problem occurs -
Try using - #XmlAccessorType(XmlAccessType.FIELD)
Move #XmlAttribute(name = "HostName") annotations to fields instead of accessor methods.
I am not sure if this is your problem. I faced a similar problem and this helped me. I wont guarantee that it will solve your problem but prima facie, it appears that above can fix it.
dbName, sid are Attributes, but you have annotated them #XmlElement. change all the attributes to #XmlAttribute.
Why don't you use
Xstream library
Example:
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
#XStreamAlias("Cat")
class Cat {
#XStreamAsAttribute
int age;
String name;
}
public class XStreamDemo {
public static void main(String[] args) {
XStream xstream = new XStream();
xstream.processAnnotations(Cat.class);
String xml = "<Cat age='4' ><name>Garfield</name></Cat>";
Cat cat = (Cat) xstream.fromXML(xml);
System.out.println("name -> " + cat.name);
System.out.println("age -> " + cat.age);
}
}
You need to add Xstream jar files in to classpath.
Use these classes.
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"value"
})
#XmlRootElement(name = "TableConfig")
public class TableConfig {
#XmlValue
protected String value;
#XmlAttribute(name = "ID")
protected Byte id;
#XmlAttribute(name = "TableName")
protected String tableName;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Byte getID() {
return id;
}
public void setID(Byte value) {
this.id = value;
}
public String getTableName() {
return tableName;
}
public void setTableName(String value) {
this.tableName = value;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"tableConfig"
})
#XmlRootElement(name = "DBConfig")
public class DBConfig {
#XmlElement(name = "TableConfig", required = true)
protected TableConfig tableConfig;
#XmlAttribute(name = "ID")
protected Byte id;
#XmlAttribute(name = "Name")
protected String name;
#XmlAttribute(name = "DriverName")
protected String driverName;
#XmlAttribute(name = "HostName")
protected String hostName;
#XmlAttribute(name = "PortName")
protected String portName;
#XmlAttribute(name = "DBName")
protected String dbName;
#XmlAttribute(name = "ServiceName")
protected String serviceName;
#XmlAttribute(name = "User")
protected String user;
#XmlAttribute(name = "PassWord")
protected String passWord;
#XmlAttribute
protected String sid;
public TableConfig getTableConfig() {
return tableConfig;
}
public void setTableConfig(TableConfig value) {
this.tableConfig = value;
}
public Byte getID() {
return id;
}
public void setID(Byte value) {
this.id = value;
}
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getDriverName() {
return driverName;
}
public void setDriverName(String value) {
this.driverName = value;
}
public String getHostName() {
return hostName;
}
public void setHostName(String value) {
this.hostName = value;
}
public String getPortName() {
return portName;
}
public void setPortName(String value) {
this.portName = value;
}
public String getDBName() {
return dbName;
}
public void setDBName(String value) {
this.dbName = value;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String value) {
this.serviceName = value;
}
public String getUser() {
return user;
}
public void setUser(String value) {
this.user = value;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String value) {
this.passWord = value;
}
public String getSid() {
return sid;
}
public void setSid(String value) {
this.sid = value;
}
}

Json Object conversion to java object using jackson

I have following json data
{"id":10606,
"name":"ProgrammerTitle",
"objectMap":{"programme-title":"TestProgramme","working-title":"TestProgramme"}
}
I want to set this data to my pojo object
public class TestObject {
private Long id;
private String name;
#JsonProperty("programme-title")
private String programmeTitle;
#JsonProperty("working-title")
private String workingTitle;
}
Here i am able to set id and name in my test object but for object map i am not able to set data.
So i have made on more class for ObjectMap which contains programmeTitle & workingTitle this works fine but i can't set this fields directly to my pojo object
is this possible to set?
I am using Jackson Object Mapper to convert json data.
It is working fine if i create another java object inside my pojo like:
public class TestObject {
private Long id;
private String name;
#JsonProperty("objectMap")
private ObjectMap objectMap;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ObjectMap getObjectMap() {
return objectMap;
}
public void setObjectMap(ObjectMap objectMap) {
this.objectMap = objectMap;
}
}
public class ObjectMap {
#JsonProperty("programme-title")
private String programmeTitle;
#JsonProperty("working-title")
private String workingTitle;
public String getProgrammeTitle() {
return programmeTitle;
}
public void setProgrammeTitle(String programmeTitle) {
this.programmeTitle = programmeTitle;
}
public String getWorkingTitle() {
return workingTitle;
}
public void setWorkingTitle(String workingTitle) {
this.workingTitle = workingTitle;
}
}
If your JSON is like this
{"id":10606,
"name":"ProgrammerTitle",
"objectMap":{"programme-title":"TestProgramme","working-title":"TestProgramme"}
}
then you may write your object mapper class like this..
public class Program{
public static class ObjectMap{
private String programme_title, working_title;
public String getprogramme_title() { return programme_title; }
public String getworking_title() { return working_title; }
public void setprogramme_title(String s) { programme_title= s; }
public void setworking_title(String s) { working_title= s; }
}
private ObjectMap objMap;
private String name;
public ObjectMap getobjectMap () { return objMap; }
public void setObjectMap (ObjectMap n) { objMap= n; }
private Long id;
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
private String name;
public String getName() {return name;}
public void setName(String name) {this.name = name;}
}
please refer this check it
You can write your own deserializer for this class:
class EntityJsonDeserializer extends JsonDeserializer<Entity> {
#Override
public Entity deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
Root root = jp.readValueAs(Root.class);
Entity entity = new Entity();
entity.setId(root.id);
entity.setName(root.name);
if (root.objectMap != null) {
entity.setProgrammeTitle(root.objectMap.programmeTitle);
entity.setWorkingTitle(root.objectMap.workingTitle);
}
return entity;
}
private static class Root {
public Long id;
public String name;
public Title objectMap;
}
private static class Title {
#JsonProperty("programme-title")
public String programmeTitle;
#JsonProperty("working-title")
public String workingTitle;
}
}
Your entity:
#JsonDeserialize(using = EntityJsonDeserializer.class)
class Entity {
private Long id;
private String name;
private String programmeTitle;
private String workingTitle;
//getters, setters, toString
}
And usage example:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class JacksonProgram {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Entity entity = mapper.readValue(jsonString, Entity.class);
System.out.println(entity);
}
}
Above program prints:
Entity [id=10606, name=ProgrammerTitle, programmeTitle=TestProgramme, workingTitle=TestProgramme]

Categories