I am using JSON Serialization. Here is my code.
I need to change the qualified class name using Annotation. I don't have to use Map or another class. Name should be picked from Annotation.
package com.test;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
#JsonTypeName("Product")
#JsonRootName("Product")
#JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
public class ProductDTO {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Test Class:-
package com.test;
import java.io.IOException;
import java.util.ArrayList;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ProductDTOTestCase {
#Test
public void testPersistAndFindById() throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping();
//mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE, JsonTypeInfo.As.WRAPPER_ARRAY);
ProductDTO productDTO = new ProductDTO();
productDTO.setDescription("Product 4 - Test");
ArrayList<ProductDTO> arrayList = new ArrayList<ProductDTO>();
arrayList.add(productDTO);
// Do not change this line
String writeValueAsString = mapper.writeValueAsString(arrayList);
System.out.println(writeValueAsString);
// /Assert.assertTrue(writeValueAsString.contentEquals("Entity"));
}
}
It gives me:-
[["com.test.ProductDTO",{"name":null,"description":"Product 4 - Test"}]]
But I want
[["Product",{"name":null,"description":"Product 4 - Test"}]]
Problem is that you serialize basically a generic ArrayList (the Class of your ArrayList, since no generic info is available).
As a consequence, our basic List.class has simply no #JsonTypeInfo annotation or whatsoever about the items contained, no type information is available, that's why you get the simple name of your class.
Solutions:
Use custom sub-class like "class MyList extends ArrayList { }" --> it will NOT suffer from this kind of type erasure (generic type info is hidden, but retained) and will work as expected, OR
Use ObjectWriter and specify full generic type in your serialization: mapper.writerForType(listType).writeValueAsString() (listType you can construct using TypeFactory or using TypeReference)
Related
Is it possible to deserialize the following class with Jackson?
So the original version of the question wasn't entirely accurate. Here's a minimal example to reproduce the problem.
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;
#JsonIdentityInfo(
generator = ObjectIdGenerators.IntSequenceGenerator.class,
property = "id")
public class Thing {
public Thing thing;
#JsonCreator
public Thing(#JsonProperty("thing") Thing thing) {
this.thing = thing;
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Thing cyclic = new Thing(null);
cyclic.thing = cyclic;
String serialised = mapper.writeValueAsString(cyclic);
System.out.println(serialised);
Thing deserialised = mapper.readerFor(Thing.class).readValue(serialised);
System.out.println(deserialised.thing == deserialised);
}
}
This causes the unresolved forward reference exception. The issue seems to be that Jackson is told to use the annotated constructor, but it can't due to the cyclic dependency.
The solution is to add a default constructor, and remove the #JsonProperty and #JsonCreator annotations.
I have a class with #XmlAccessorType(XmlAccessType.FIELD) annotation, and each private and protected field is annotated with #XmlElement(name='...').
The challenge: I may want to rename one of the xml element names in a later stage. This leads me to the question. Is there a way to override/redefine these annotations, if I create a sub-class ?
I believe that some implementations of JaxB allow for XML configuration to override the annotations. In this case this may actually be possible. Here is an article from Eclipslink explaining how this can be done http://www.eclipse.org/eclipselink/documentation/2.4/solutions/jpatoxml004.htm
In my opinion you can just build an XML configuration for the JaxB file you want to override.
I tried first with the #XmlAccessorType(XmlAccessType.FIELD) and to hide with #XmlTransient. This only works, if you mark the field in the superclass and in the child class with #XmlTransient. But I assume, this is not what you want.
As second approach I've tried with more restrictive #XmlAccessorType(XmlAccessType.PROPERTY) in the superclass and #XmlAccessorType(XmlAccessType.NONE) in the child class. See here my example:
package com.so.example;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/myresource")
public class MyResource {
#GET
#Path("/car")
#Produces(MediaType.APPLICATION_XML)
public Car getCar() {
Car car = new Car();
car.setWheels(4);
return car;
}
#GET
#Path("/suv")
#Produces(MediaType.APPLICATION_XML)
public Suv getSuv() {
Suv suv = new Suv();
List<String> bigWheels = new ArrayList<>();
bigWheels.add("left front wheel");
bigWheels.add("right front wheel");
bigWheels.add("left rear wheel");
bigWheels.add("right rear wheel");
suv.setBigWheels(bigWheels);
return suv;
}
}
Class Car:
package com.so.example;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.PROPERTY)
#XmlRootElement
public class Car {
protected Integer wheels;
public Car() {
}
#XmlElement(name = "wheels", nillable = true)
public Integer getWheels() {
return wheels;
}
public void setWheels(Integer wheels) {
this.wheels = wheels;
}
}
Class Suv (Child):
package com.so.example;
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.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
#XmlRootElement
#XmlAccessorType(XmlAccessType.NONE)
public class Suv extends Car {
#XmlTransient
private Integer wheels;
private List<String> bigWheels;
public Suv() {
}
#Override
#XmlTransient
public Integer getWheels() {
return wheels;
}
#Override
public void setWheels(Integer wheels) {
this.wheels = wheels;
}
#XmlElement
public List<String> getBigWheels() {
return bigWheels;
}
public void setBigWheels(List<String> bigWheels) {
this.bigWheels = bigWheels;
}
}
One way to "hide" the element wheels of the superclass would be to mark it as "nillable=true" and not use primitive types. In this case, the field wheels will be marshalled to <wheels xsi:nil="true"/>
If it's possible for you to not use the parent class for marshalling and you are only using child classes, you could use the approach described here:
http://blog.bdoughan.com/2011/06/ignoring-inheritance-with-xmltransient.html
Also you could use moxy and specify a custom binding:
http://www.eclipse.org/eclipselink/documentation/2.4/moxy/runtime003.htm
Whilst in java, to my knowledge, overriding an annotation #XmlElement(name='...') to change the name property is not possible; you can create a global variable in your code and either pass it through your classes or your functions following the #XmlElement(name='...').
In the code below I created a single class but it contains the setter and getter methods required if you want to pass it through to another class
#XMLAccessorType(XMLAccessType.FIELD)
public class YourClass {
#XmlTransient
private String string = ""; //This can be replaced with whatever variable you are manipulating
//That could be an int or a file or anything really
#XmlElement(name = "your_name")
private void doSomething() {
String temp = getString(); //This variable is normally used to pass between different
//classes but may as well use it if you have one
//Your code which manipulates the String
setString(temp); //This variable is normally used to pass between different classes but
//may as well use it if you have one
}
#XmlElement(name = "your_other_name")
private void doSomethingElse() {
String temp = getString();
//Your code which manipulates the String
setString(temp);
}
public void getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
}
I would reccomend looking at the Java Docs for #XmlTransient and these two other relevant SO questions.
How to override JAXB #XMLAccessorType(XMLAccessType.FIELD) specified at a Class level with #XMLElement on a getter method for a property?
Jaxb - Overriding the XMLElement name attribute
I am using Jackson ObjectMapper to (de)serialize a class with polymorphic nested class. The deserialization of JSON to the class is working fine but when I try to serialize the class to JSON using writeValueAsString function I observe duplicate values in the output
public class Movie {
private String movieName;
#JsonTypeInfo(use=Id.NAME,include=As.EXTERNAL_PROPERTY,property="movieName")
#JsonSubTypes({#JsonSubTypes.Type(value = StarWarsParams.class, name = "starwars")})
private MovieParams movieParams;
/* Getters and setters follow */
}
/* Empty class */
public class MovieParams {
}
public class StarWarsParams extends MovieParams{
private String characterName;
#JsonTypeInfo(use=Id.NAME,include=As.EXTERNAL_PROPERTY,property="characterName")
#JsonSubTypes({#JsonSubTypes.Type(value = SithParameters.class, name = "Darth Vader")})
private CharacterParams characterParams;
/* Getters and setters follow */
}
/* Empty class */
public class CharacterParams {
}
public class SithParameters extends CharacterParams {
private boolean canShootLightning;
}
The code snippet where the conversion is done as follows:
Movie movie = new Movie();
movie.setMovieName("starwars");
StarWarsParams starWarsParams = new StarWarsParams();
starWarsParams.setCharacterName("Darth Vader");
SithParameters sithParameters = new SithParameters();
sithParameters.setCanShootLightning(false);
starWarsParams.setCharacterParams(sithParameters);
movie.setMovieParams(starWarsParams);
ObjectMapper mapper = new ObjectMapper();
String jsonStringSample = mapper.writeValueAsString(movie);
System.out.println(jsonStringSample);
The output, in which movieName and characterName have duplicates are as follows:
{"movieName":"starwars","movieParams":{"characterName":"Darth Vader","characterParams":{"canShootLightning":false},"characterName":"Darth Vader"},"movieName":"starwars"}
This problem appears with older versions of Jackson e.g. 1.9.2 but not the latest ones from com.fasterxml. Jackson identifies 2 fields one from the #JsonTypeInfo annotation and one from the getter. Two solutions :
Use a more recent version of Jackson from com.fasterxml
Move the #JsonTypeInfo annotation over the getter instead of over the field e.g.
#JsonTypeInfo(use = Id.NAME, include = As.EXTERNAL_PROPERTY, property = "characterName")
public String getCharacterName() {
return characterName;
}
Customized JSON Object using Serialization is Very Simple.
I have wrote a class in my project to get Serialized JSONObject. i am giving u a Idea to how to Implement this in Project.
Application (POJO Class)
import java.io.Serializable;
import java.util.List;
import org.webservice.business.serializer.ApplicationSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
#JsonSerialize(using=ApplicationSerializer.class)
public class Application implements Serializable {
private static final long serialVersionUID = 1L;
private double amount;
private String businessType;
private String currency;
private int duration;
}
Now ApplicationSerializer class that contains the Customization using Serialization Logic................
package org.webservice.business.serializer;
import java.io.IOException;
import org.webservice.business.dto.Application;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class ApplicationSerializer extends JsonSerializer<Application> {
#Override
public void serialize(Application prm_objObjectToSerialize, JsonGenerator prm_objJsonGenerator, SerializerProvider prm_objSerializerProvider) throws IOException, JsonProcessingException {
if (null == prm_objObjectToSerialize) {
} else {
try {
prm_objJsonGenerator.writeStartObject();
prm_objJsonGenerator.writeNumberField("amount", prm_objObjectToSerialize.getAmount());
prm_objJsonGenerator.writeNumberField("duration", prm_objObjectToSerialize.getDuration());
prm_objJsonGenerator.writeStringField("businesstype", prm_objObjectToSerialize.getBusinessType());
prm_objJsonGenerator.writeStringField("currency", prm_objObjectToSerialize.getCurrency());
} catch (Exception v_exException) {
v_exException.printStackTrace()
} finally {
prm_objJsonGenerator.writeEndObject();
}
}
}
I have a base class declared something like:
package com.mystuff.surrogates;
import java.io.Serializable;
import java.util.UUID;
public class BaseClass implements Serializable {
private UUID id;
private String name;
public UUID getId() { return this.id; }
public void setId(UUID id) { this.id = id; }
public String getName() { return thisname; }
public void setName(String name) { this.name = name; }
}
And a derived class which looks something like:
package com.mystuff.surrogates;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class DerivedClass extends BaseClass {
private String email;
public String getEmail() { return this.email; }
public void setEmail(String email) { this.email = email; }
}
Finally I have a class which I am trying to return as an object from a RESTful webservice call which includes a collection of BaseClass derived class instances and looks rather like:
package com.mystuff.surrogates;
import java.util.ArrayList;
import java.util.List;
public class Response {
List<BaseClass> objectList;
public List<BaseClass> getObjectList() { return this.objectList; }
public void setObjectList(List<BaseClass> objectList) { this.objectList = objectList; }
public void addObject(BaseClass obj) {
if (this.objectList == null) {
this.objectList = new ArrayList<>();
}
this.objectList.add(obj);
}
}
When marshaling this into either XML or JSON, only the members in the base class are included. How do I get Jersey / MOXy to marshal the entire class instance rather than just the base class members? While I have only shown here one derived class, I have several others I would like to potentially chose from to return in the list, so simply using List<DerivedClass> isn't an option since it would preclude returning any of those other classes in the list.
Other information:
Netbeans 8.0.2
Glassfish 4.1 (locally hosted)
Oracle JDK 8U31 (64 bit Windows)
Java EE 7
You'll need to use #XmlSeeAlso so the other classes are binded.
#XmlSeeAlso({DerivedClass.class})
public class BaseClass {
This may not get you the exact desired result, as the marshalled data will have a reference to the type. For instance with XML, you will see
<objectList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="derivedClass">
and JSON you will see
{"objectList":[{"type":"derivedClass",...
You can have a look at this answer for an idea of how to get rid of the type property if it's undesired.
As far as the JSON is concerned, using Jackson will not have this behavior. You can simply use jersey-media-json-jackson, which Glassfish also comes shipped with (you can add it as a dependency in a provided scope), and just register the JacksonFeature with the application.
I'm able to generate the XML I want using #JacksonXmlProperty annotations with the default mapper configuration. But my classes are generated by maven-jaxb2-plugin and already have the #XmlAttribute annotations. When I try using the JaxbAnnotationIntrospector it serializes the attributes as child elements. What am I doing wrong?
Expected output: <problem xmlns="" id="aaa"><description>test</description></problem> (repeatable with testGenerateXmlCorrect)
Actual output: <problem xmlns=""><id>aaa</id><description>test</description></problem> (repeatable with testGenerateXmlWrong)
I can also generate the expected XML using JAXB but this question is how to do it with Jackson using the JaxbAnnotationIntrospector.
Junit test:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.junit.Test;
public class JaxbAttributeTest {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(JaxbAttributeTest.class);
#XmlRootElement(name="problem")
public static class ProblemJaxb {
#XmlAttribute(name="id")
public String id;
public String description;
}
#Test
public void testGenerateXmlWrong() throws JsonProcessingException {
ProblemJaxb problem = new ProblemJaxb();
problem.id = "aaa";
problem.description = "test";
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(xmlMapper.getTypeFactory()));
log.debug("ProblemJaxb: {}", xmlMapper.writeValueAsString(problem));
}
#JacksonXmlRootElement(localName="problem")
public static class ProblemJackson {
#JacksonXmlProperty(isAttribute=true)
public String id;
public String description;
}
#Test
public void testGenerateXmlCorrect() throws JsonProcessingException {
ProblemJackson problem = new ProblemJackson();
problem.id = "aaa";
problem.description = "test";
XmlMapper xmlMapper = new XmlMapper();
log.debug("ProblemJackson: {}", xmlMapper.writeValueAsString(problem));
}
}
Classpath includes:
com.fasterxml.jackson.core:jackson-core:jar:2.3.2
com.fasterxml.jackson.core:jackson-annotations:jar:2.3.2
com.fasterxml.jackson.core:jackson-databind:jar:2.3.2
com.fasterxml.jackson.dataformat:jackson-dataformat-xml:jar:2.3.2
com.fasterxml.jackson.module:jackson-module-jaxb-annotations:jar:2.3.2
org.codehaus.woodstox:stax2-api:jar:3.1.1
javax.xml.stream:stax-api:jar:1.0-2
com.sun.xml.bind:jaxb-impl:jar:2.2.7
com.sun.xml.bind:jaxb-core:jar:2.2.7
javax.xml.bind:jaxb-api:jar:2.2.7
By the way I also tried configuring the XmlMapper with this:
xmlMapper.getSerializationConfig().with(new JaxbAnnotationIntrospector(xmlMapper.getTypeFactory()));
but that generated even worse output because the root element name was incorrect: <ProblemJaxb xmlns=""><id>aaa</id><description>test</description></ProblemJaxb>
It looks like this problem existed before, but was not reproducible by the writers of Jackson. It doesn't seem like the bug report went very far.
I was able to solve the problem by using XmlJaxbAnnotationIntrospector instead of JaxbAnnotationIntrospector.