Stop converting < to &lt, > to &gt and & to & in spring controller response - java

I am trying to generate a small xml. This xml should have a CDATA in it. Now the problem is I managed to generate CDATA, but the xml that is generated have < and > and &
I am using spring-mvc. I am interested in getting the right xml with CDATA in it.
Sample xml is as follow :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Customer>
<Active>1</Active>
<AlertMessage></AlertMessage>
<Currency>GBP</Currency>
<CustomerNumber>123</CustomerNumber>
<Forename>AD</Forename>
<balancetoallow>
<balance saving="10" spend="9990" type="2">
<value>\<![CDATA[$100 off on two purchase of jeans XYZ Brand.]]\></value>
</balance>
</balancetoallow>
<Surname>CD</Surname>
</Customer>
I have also overridden one of the converter as follow.
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
P.S I am using spring rest controller for my web service.
Here is the model class :
public class Balance{
private String value;
private String type;
private String saving;
private String spend;
public String getValue() {
return value;
}
#XmlJavaTypeAdapter(AdapterCDATA.class)
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
#XmlAttribute
public void setType(String type) {
this.type = type;
}
public String getSaving() {
return saving;
}
#XmlAttribute
public void setSaving(String saving) {
this.saving = saving;
}
public String getSpend() {
return spend;
}
#XmlAttribute
public void setSpend(String spend) {
this.spend = spend;
}
}
This class is again part of another class.
public class Balancetoallows {
private List<Balance> balancetoallow ;
public List<Balance> getBalancetoallow () {
return balancetoallow;
}
#XmlElement(name="balancetoallow ")
public void setBalancetoallow (List<Balance > balancetoallow ) {
this.balancetoallow= balancetoallow;
}
}
And this is part of this class.
The parent class.
#XmlRootElement(name = "Customer")
public class Customer {
private String surname ;
private String forename;
private BalanceToAllow balanceToAllow;
private final String active="1";
private final String currency = "GBP";
private final String alertMessage="";
public String getCustomerNumber() {
return customerNumber;
}
#XmlElement(name="CustomerNumber")
public void setCustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}
#XmlElement(name="Active")
public String getActive() {
return active;
}
#XmlElement(name="Currency")
public String getCurrency() {
return currency;
}
public String getSurname() {
return surname;
}
#XmlElement(name="Surname")
public void setSurname(String surname) {
this.surname = surname;
}
public String getForename() {
return forename;
}
#XmlElement(name="Forename")
public void setForename(String forename) {
this.forename = forename;
}
#XmlElement(name="AlertMessage")
public String getAlertMessage() {
return alertMessage;
}
public BalanceToAllow getBalanceToAllow() {
return BalanceToAllow;
}
#XmlElement(name="balanceToAllow")
public void setFuturePromotions(BalanceToAllow balanceToAllow) {
this.balanceToAllow= balanceToAllow;
}
}
Thanks for reading.

Related

How to create Gson object for entity class which has timestamp value?

I have a payload string and want to change it to values of entity. The payload as below:
{"resultCode":"200","resultMessage":"Success","consent":[{"name":"A","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"1.0","updateDate":1600658621871},{"name":"B","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"2.0","updateDate":1874819158457},{"name":"C","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"3.0","updateDate":1358819159457}]}
And the entities:
public class ListConsentResponse {
private String resultCode;
private String resultMessage;
private List<ConsentDTO> consent;
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public List<ConsentDTO> getConsent() {
return consent;
}
public void setConsent(List<ConsentDTO> consent) {
this.consent = consent;
}
}
public class ConsentDTO {
private String name;
private String sourceSystem;
private String updateBy;
private String remark;
private String version;
private Timestamp updateDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSourceSystem() {
return sourceSystem;
}
public void setSourceSystem(String sourceSystem) {
this.sourceSystem = sourceSystem;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Timestamp getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Timestamp updateDate) {
this.updateDate = updateDate;
}
}
But when I parse to json using GsonBuilder :
ListConsentResponse listConsentResponse = Utility.createGsonObject()
.fromJson(payload, ListConsentResponse.class);
I have error:
com.google.gson.JsonSyntaxException: 1600658621871
Is there any way help me get parse the string with Timestamp value to entity. Or at least can I change the Timestamp value to String value in payload (For example change 1600658621871 to "1600658621871").
Thanks.

Gson-xml deserialize list<object> in onother list<object>

i use Gson-xml library to cast xml to object. this is my xml:
<GetSentMessageListResponse xmlns="http://ICAN.ir/x/mWebServices/">
<GetSentMessageListResult>
<Message>
<ID>2620</ID>
<Subject>test</Subject>
<Description>&lt;div style=&quot;font-family:Tahoma;font-size:20pt&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/div&gt;</Description>
<SentDate>7/10/2018 5:04:40 PM</SentDate>
<Receivers>
<Receiver>
<RoleID>393</RoleID>
<UserID>717</UserID>
<UserName>f</UserName>
<NativeID />
</Receiver>
<Receiver>
<RoleID>786</RoleID>
<UserID>5</UserID>
<UserName>mm</UserName>
<NativeID />
</Receiver>
</Receivers>
<MessageFiles />
</Message>
</GetSentMessageListResult>
<strErrorMsg />
</GetSentMessageListResponse>
and blow are my class:
public class StructureMessageListResultOP {
private StructureMessageList GetRecieveMessageListResult;
private StructureMessageList GetSentMessageListResult;
private String StrErrorMsg;
public StructureMessageList getGetRecieveMessageListResult() {
return GetRecieveMessageListResult;
}
public void setGetRecieveMessageListResult(StructureMessageList getRecieveMessageListResult) {
GetRecieveMessageListResult = getRecieveMessageListResult;
}
public StructureMessageList getGetSentMessageListResult() {
return GetSentMessageListResult;
}
public void setGetSentMessageListResult(StructureMessageList getSentMessageListResult) {
GetSentMessageListResult = getSentMessageListResult;
}
public String getStrErrorMsg() {
return StrErrorMsg;
}
public void setStrErrorMsg(String strErrorMsg) {
StrErrorMsg = strErrorMsg;
}
//____________________________________________________
public class StructureMessageList {
List<StructureMessageListBodyOP> Message;
public List<StructureMessageListBodyOP> getMessage() {
return Message;
}
public void setMessage(List<StructureMessageListBodyOP> message) {
Message = message;
}
}
}
public class StructureMessageListBodyOP {
private int ID;
private String Subject;
private String Description;
private String SentDate;
StructureReceiverList Receivers;
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getSubject() {
return Subject;
}
public void setSubject(String subject) {
Subject = subject;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getSentDate() {
return SentDate;
}
public void setSentDate(String sentDate) {
SentDate = sentDate;
}
public StructureReceiverList getReceivers() {
return Receivers;
}
public void setReceivers(StructureReceiverList receivers) {
Receivers = receivers;
}
//-------------------------- **ReceiverList** -------------------------------
public class StructureReceiverList {
List<StructureReceiverOP> Receiver;
public List<StructureReceiverOP> getReceiver() {
return Receiver;
}
public void setReceiver(List<StructureReceiverOP> receiver) {
Receiver = receiver;
}
}
//___________________________________________________________________________
}
public class StructureReceiverOP {
private int RoleID;
private int UserID;
private String UserName;
public int getRoleID() {
return RoleID;
}
public void setRoleID(int roleID) {
RoleID = roleID;
}
public int getUserID() {
return UserID;
}
public void setUserID(int userID) {
UserID = userID;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
}
my problem is Gson-xml can not cast inerList and when write
List<StructureReceiverOP> Receiver;
set error and can not cast.
please help me i got tired.
I tried it anyway, but did not.
I thought the library was very powerful, but it was not like that.
If you know a better library that can do that, tell me. Mention
i tried many time and finaly found another library which use the java core.
i used Simple-xml.you can use it from this Link

How to Parse below XML using java?

Iam trying to get Status and message tag info using java 1.7
Please any guide me ,
Thanks in advance
<API version="0.0">
<response>
<operation name="ADD">
<result>
<statuscode>200</statuscode>
<status>Success</status>
<message> successfully</message>
</result>
<Details type="ADD"/>
</operation>
</response>
</API>
This is not a JSON response that you are getting, it's an XML response,
you just need to convert the XML response to POJO class and use the POJO class instead.
Here is how the POJO class will look like
public class MyPojo{
private API API;
public API getAPI() {
return API;
}
public void setAPI(API API) {
this.API = API;
}
}
now MyPojo will contain another class named API
public class API {
private Response response;
private String version;
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
now the API class contains another class called Response
public class Response {
private Operation operation;
public Operation getOperation() {
return operation;
}
public void setOperation(Operation operation) {
this.operation = operation;
}
}
Now the Response class is containing another class called Operation
public class Operation {
private Result result;
private Details Details;
private String name;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public Details getDetails() {
return Details;
}
public void setDetails(Details Details) {
this.Details = Details;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now you guessed it the Operation class is containing two classes Details and Result
Here is the Result class that is containing the status and message you want to access
public class Result {
private String message;
private String status;
private int statuscode;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getStatuscode() {
return statuscode;
}
public void setStatuscode(int statuscode) {
this.statuscode = statuscode;
}
}
Here is the Details class
public class Details {
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
finally, you can access the status and message by creating an object from MyPojo class like this:
String message = myPojo.getAPI().getResponse().getOperation().getResult().getMessage();
String status = myPojo.getAPI().getResponse().getOperation().getResult().getStatus();
you can use this online converter to convert XML/JSON to POJO.
I hope my answer was helpful :)

Parsing XML data into string objects using JAXB

I have to parse a xml into string objects in JAXB. But how to creates objects for this xml
Country.xml
<?xml version="1.0" encoding="UTF-8"?>
<Country>
<name>India</name>
<capital>New Delhi</capital>
<population>120crores</population>
.
.
.
.
.
<states>
<state>
<name>Maharastra</name>
<pincode>xyzzzz</pincode>
<capital>Mumbai</capital>
<\state>
<state>
.
.
.
</state>
</states>
<\Country>
And to parse this xml I have created class to map the objects which creates the objects and print it in the console. But Don't know what I am doing wrong.
#XmlElementWrapper(name="Country")
public void setCountry(String Countryv) {
Country= Countryv;
}
#XmlElement (name = "name")
public void setname(String namev) {
name= namev;
}
#XmlElement (name = "capital")
public void setcapital(String capitalv) {
capital= capitalv;
}
#XmlElement (name = "population")
public void setpopulation(String populationv) {
population= populationv;
}
#XmlElementWrapper(name="states")
public void setType(String statesv) {
states = statesv;
}
#XmlElementWrapper(name="state")
public void setType(String statev) {
state = statev;
}
#XmlElement (name = "name")
public void setpopulation(String namev) {
name= namev;
}
#XmlElement (name = "pincode")
public void setpopulation(String pincodev) {
pincode= pincodev;
}
#XmlElement (name = "capital")
public void setpopulation(String capitalv) {
capital= capitalv;
}
when I run the program I m getting the
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:
counts of IllegalAnnotationExceptions
How to add wrapper anotations to wrapping the elements under separate headers and headers inside other headers.
Try this class
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"name",
"capital",
"population",
"states"
})
#XmlRootElement(name = "Country")
public class Country {
#XmlElement(required = true)
protected String name;
#XmlElement(required = true)
protected String capital;
#XmlElement(required = true)
protected String population;
#XmlElement(required = true)
protected Country.States states;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getCapital() {
return capital;
}
public void setCapital(String value) {
this.capital = value;
}
public String getPopulation() {
return population;
}
public void setPopulation(String value) {
this.population = value;
}
public Country.States getStates() {
return states;
}
public void setStates(Country.States value) {
this.states = value;
}
This worked for me
class Country {
#XmlElement
String name;
//...
#XmlElementWrapper(name="states")
List<State> state;
}
class State {
#XmlElement
String name;
//..
}

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;
}
}

Categories