How to deserialize XML element with package name using Xstream? - java

I have an xml response and trying to convert it to java object using Xstream library.
<products>
<com.example.model.ProductModel>
<productDefinition>
<productId>1</productId>
<productType>ASD</productType>
<price>10</price>
</productDefinition>
</com.example.model.ProductModel>
</products>
Here are my java classes for this:
#XStreamAlias("products")
public class Product {
#XStreamImplicit(itemFieldName="com.example.model.ProductModel")
private ProductModel productModel;
//getters, setters
}
public class ProductModel {
#XStreamImplicit(itemFieldName="productDefinition")
private ProductDefinition productDefinition;
//getters, setters
}
When I convert this xml to java object, Product object is not null, but the ProductModel inside of it becomes null. I guess the problem is about the full package name of the xml tag. Any suggestions about how to solve it?
Thanks.

I found the soultion, XStream aliasField method helped me solve it.
xstream.aliasField("com.example.model.ProductModel", Product.class, "productModel");
This simply means, map the "com.example.model.ProductModel" element in the xml to productModel object of Product class.

Related

Using JAXB, marshal nested element in JAVA

I would like to get a xml result as below which using JAXB to get java object.
<Mall>
<ProductInfo>
<Product>
<name>chair</name>
<price>150</price>
</Product>
</ProductInfo>
</Mall>
To get this result, I made 3 java classes which are
Define XmlRootElement, XmlElement
component of product (getter/setter)
Main class which insert the value of component
In this way, I could make only 3 depths using XmlRootElement, XmlElement, Component of product.
Hence I need one more depth..
I tried to use a XmlElementWrapper to give one more depth, but there was an error regarding it is not a collecting attribute...
Please help me to solve this out...
Below is class structure that should work
#XmlRootElement (name = "mall")
public class Mall {
Mall(){ }
#XmlElement(name="ProductInfo")
private ProductInfo info; // must create getter and setter
}
}
public class ProductInfo { // you should be missing this
ProductInfo(){
}
#XmlElement(name="Product")
private List<Product> info; // must create getter and setter
}
}
public class Product {
Product(){
}
#XmlElement(name="name")
private ProductInfo info; // must create getter and setter
#XmlElement(name="price")
private ProductInfo info; // must create getter and setter
}
}

How to parse DTO to Pojo objects

Well, I'm trying to parse objects and I'm having so much issues.
My classes are like this:
-Entidad-
public class Entidad{
private Long codEntidad;
private Set<Comunicacion> comunicacion;
/*------------ Getter and Setters --------------*/
}
-Comunicacion-
public class Comunicacion {
private Entidad entidad;
private Long codComunicacion;
/*------------ Getter and Setters --------------*/
}
I need to parse to DTO objects:
-EntidadDTO-
public class EntidadDTO{
private Long codEntidad;
private Set<ComunicacionDTO> comunicacionDto;
/*------------ Getter and Setters --------------*/
}
-ComunicacionDTO-
public class ComunicacionDTO {
private EntidadDto entidadDto;
private Long codComunicacion;
/*------------ Getter and Setters --------------*/
}
I tried to use:
BeanUtils.copyProperties(entidad, entidadDto);
It seems that the parse is success but the property entidadDto.getComunicacionDto(); is a hashMap of Comunicacion (not ComunicacionDTO)
Should I try to make a custom parse with reflection?
Also I'd like to use this to parse more objects with a similar structure.
Thanks!
Try dozer. You can define mappings from bean to bean using it.
http://dozer.sourceforge.net/
Why you want to parse java object and move data to other java object?
Parsing is for unstructured strings not for objects.
Use setters/getters to move data from one object to the other, using reflection will make you cry when you start doing refactorings.

Jackson JSON XML - different names when serializing to XML

I'd like to have different name for my element when it's serialized to XML (for example "fooXml") and different for JSON (for example "fooJson"). Is it possible?
I'm using XML annotations like:
#XmlElements({
#XmlElement(type = Foo.class, name = "fooXml"),
})
private SortedSet<Foo> fooSet;
I've tried already #JsonProperty, with without any luck.
I've also tried exporting it to getter method, like:
#XmlElement(type = Foo.class, name = "fooXml")
#JsonProperty(value = "fooJson")
public List<Foo> getFooList() {
return new ArrayList<>(fooSet);
}
But it's always ignoring JSON annotations and serializing to XML form (fooXml name).
How shall I do it?
edit: I'm using Jersey-json.
Alright, I had a need for this same functionality and found a solution that works for this:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
#JsonProperty("MyJsonName")
#JacksonXmlProperty(localName = "MyXmlName")
private MyProperty myProperty;
Works for me, and myProperty will be in the 'MyJsonName' field in Json and the 'MyXmlName' in XML.

Embedded attributes in JAXB class

I need to map some legacy XML I can't change. There are several elements that have hundreds attributes exactly the same as some other elements. The attributes all have the same name postfixed with a number. So XML might look like this:
<someElement custom1="..." custom2="..." custom78=".."/>
<anotherElmenent custom1="..." custom45="..."/>
A solution that "works" is to create a base class like so:
#XmlAccessorType(FIELD)
public class LotsaCustomIds
{
#XmlAttribute
private String custom1;
#XmlAttribute
private String custom2;
...
}
#XmlType
public class SomeElement extends LotsaCustomIds
{
....
}
But it's a shame to use inheritence here, especially since Java only has single inheritence. What I'd like to do is something like the way JPA/Hibernate do embedded objects, like:
#XmlType
public class SomeElement
{
#EmbeddedAttributes
private LotsaCustomIds customIds;
....
}
Anyway to do this?
Note: I'm the EclipseLink JAXB (MOXy) lead.
You could use MOXy's #XmlPath extension to map this use case. When you use it as #XmlPath(".") then it will pull the contents of the child object (LotsaCustomIds) into the parent object (SomeElement).
#XmlType
public class SomeElement
{
#XmlPath(".")
private LotsaCustomIds customIds;
....
}
Related Information from my Blog
http://blog.bdoughan.com/2010/07/xpath-based-mapping.html

How to convert single element to arraylist and format to json using jersey?

Jersey by default convert single element returned to object . But the client side is expecting the data in json to be arraylist
Model class is LocationDetails
public class LocationDetails {
private String locationAccount;
private String locationName;
private String locationStreet;
private String locationPostcode;
}
other class LocationData which has arraylist of LocationDetails as
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class LocationData {
private ArrayList<LocationDetails> Locations;
}
and the controller class is using the following code to convert to JSON:
//Getting location and item along with barcodes
#POST
#Path("/getLocationAndItemData")
#Produces(MediaType.APPLICATION_JSON)
public LocationResponse getAlllocations(){
ArrayList<LocationDetails> locationDetailList = new ArrayList<LocationDetails>();
LocationDetails details = new LocationDetails();
//setting location account
details.setLocationAccount("10125");
locationDetailList.add(details);
}
The following code is returning json as LocationData : {LocationDetails : {"LocationAccount","10125"}}
whereas i want it to be like :
LocationData : {LocationDetails : [{"LocationAccount","10125"}]}
as the client side would expect the data to be inside list.
How to convert the type without changing the whole logic.I am using jersey.
Add #XmlElementWrapper annotation to your List, that should do the trick. If you have further problems with Jersey, try first XML output to see what is being produced. If XML is ok, JSON will be too.
#XmlElement(name="locationDetail")
#XmlElementWrapper(name="locationDetails")
private List<LocationDetail> locationDetails;
Also name your class properties with first lowercase letter, please.
I too had the same issue, after so many research i found that the problem is due to the jar files imported in the MyEclipse (Persisted container). I have removed that. The same code works for me.
The json format will be [{single element}].

Categories

Resources