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.
Related
I use jackson ObjectMapper to serialize and deserialize some data of mine, which have fields of javaslang Option type. I use JavaslangModule (and Jdk8Module). And when it write the json, Option.None value fields are written as null.
To reduce the json size and provide some simple backward compatibility when later adding new fields, what I want is that:
fields with Option.None value are simply not written,
missing json fields that correspond to data model of Option type, be set to Option.None upon reading
=> Is that possible, and how?
Note:
I think that not-writing/removing null json fields would solve (1). Is it possible? And then, would reading it works (i.e. if model field with Option value is missing in the json, set it None?
Luckily there is a much simpler solution.
1) In your ObjectMapper configuration, set serialization inclusion to only include non absent field:
#Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModules(vavr());
objectMapper.setSerializationInclusion(NON_ABSENT);
return objectMapper;
}
2) Set the default value of your optional fields to Option.none:
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Foo {
private Option<String> bar = Option.none(); // If the JSON field is null or not present, the field will be initialized with none
}
That's it!
And the even better news is that it works for all Iterables, not just for Option. In particular it also works for Vavr List type!
I found a solution that works with immuatble (lombok #Value) models:
add a filter on all Object using mixIn that doesn't write Option.None (see "the solution" below)
my existing ObjectMapper (with JavaslangModule) is already setting None to Option field when the corresponding json entry is missing
The code
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import javaslang.control.Option;
import javaslang.jackson.datatype.JavaslangModule;
import lombok.AllArgsConstructor;
import lombok.Value;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.Field;
public class JsonModelAndSerialization {
// Write to Json
// =============
private static ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new Jdk8Module())
.registerModule(new JavaslangModule())
// not required but provide forward compatibility on new field
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
static String write(Object data) throws JsonProcessingException {
SimpleBeanPropertyFilter filter = new NoneOptionPropertyFilter();
objectMapper.addMixIn(Object.class, NoneOptionFilter.class);
final SimpleFilterProvider filters = new SimpleFilterProvider().setDefaultFilter(filter);
ObjectWriter writer = objectMapper.writer(filters);
return writer.writeValueAsString(data);
}
// Filter classes
// ==============
#JsonFilter("Filter None")
private static class NoneOptionFilter {}
private static class NoneOptionPropertyFilter extends SimpleBeanPropertyFilter {
#Override
public void serializeAsField(
Object pojo, JsonGenerator jgen,
SerializerProvider provider, PropertyWriter writer) throws Exception{
Field field = pojo.getClass().getDeclaredField(writer.getName());
if(field.getType().equals(Option.class)){
field.setAccessible(true);
Option<?> value = (Option<?>) field.get(pojo);
if(value.isEmpty()) return;
}
super.serializeAsField(pojo, jgen, provider, writer);
}
}
// Usage example
// =============
// **important note**
// For #Value deserialization, a lombok config file should be added
// in the source folder of the model class definition
// with content:
// lombok.anyConstructor.addConstructorProperties = true
#Value
#AllArgsConstructor(onConstructor_={#JsonCreator})
public static class StringInt {
private int intValue;
private Option<String> stringValue;
}
#Value
#AllArgsConstructor(onConstructor_={#JsonCreator})
public static class StringIntPair {
private StringInt item1;
private StringInt item2;
}
#Test
public void readWriteMyClass() throws IOException {
StringIntPair myClass = new StringIntPair(
new StringInt(6 * 9, Option.some("foo")),
new StringInt( 42, Option.none()));
String json = write(myClass);
// {"item1":{"intValue":54,"stringValue":"foo"},"item2":{"intValue":42}}
StringIntPair myClass2 = objectMapper.readValue(json, StringIntPair.class);
assertThat(myClass2).isEqualTo(myClass);
}
}
The advantages:
reduce size of json when having Option.None (thus adding Option fields in the model doesn't cost size when not used)
it provides backward reading compatibility when later adding field with Option type in the model (which will default to None)
The disadvantage:
It is not possible to differentiate correct data with None field value and incorrect data where the field has erroneously been forgotten. I think this is quite acceptable.
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 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 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)
I'm having an issue generating XML via Java code. I have a class that for SailingAvailabilityResponseMessage. Within this class there are several other classes that are also used in the method I'm writing. Here is a snippet of what the SailingAvailabilityResponseMessage classes looks like:
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
#XmlType(propOrder={"type", "agency", "version", "release", "processingInfo", "advisoryMessage", "packageDescription", "sailingGroup", "registrationInformation"})
public class SailingAvailabilityResponseMessage {
private ProcessingInfo processingInfo;
private AdvisoryMessage advisoryMessage;
private PackageDescription packageDescription;
private SailingGroupResponse[] sailingGroup;
private RegistrationInformation registrationInformation;
String type;
#XmlAttribute
public String getType() {
return type;
}
The specific issue I'm encountering is related to the SailingGroupResponse[] sailingGroup;
SailingGroupResponse[] inherits from sailingGroup. Here is what sailingGroup looks like:
public class SailingGroup {
private SailingDescription sailingDescription;
public SailingDescription getSailingDescription() {
return sailingDescription;
}
public void setSailingDescription(SailingDescription sailingDescription) {
this.sailingDescription = sailingDescription;
}
And here is what SailingGroupResponse[] looks like:
import javax.xml.bind.annotation.XmlType;
#XmlType(propOrder={"sailingInformation", "diningDetails", "modeOfTransportation", "currencyInfo", "packageDescription"})
public class SailingGroupResponse extends SailingGroup {
private SailingInformation sailingInformation;
private DiningDetails diningDetails;
private ModeOfTransportation modeOfTransportation;
private CurrencyInfo currencyInfo;
private PackageDescription packageDescription;
The problem I'm encountering with the XML generation is that I'm expecting a tag of <sailingGroup> which I get but then I also get a tag of <sailingGroupResponse> which I do not want as it is not part of the original specs I'm following. I'm generating the XML via WebSphere RDi. I'm on SOAP 1.2 but the business partner I'm trying to develop for is on SOAP 1.1 so instead of being able to use JAX-WS runtime, I'm having to use JAX-RPC (apache AXIS will not allow me to generate).
Is anyone familiar with JAX-RPC runtime and issues similar to the one I'm asking? If anyone knows of a good site for me to visit for additional information, I'm willing to research further although so far I've not had much success in finding an answer.
Thanks,
Caren
Introducing polymorphism into JAXB-annotated classes usually causes complications, as you're finding out.
Try this:
#XmlElement(type = SailingGroup.class)
public SailingGroupResponse[] getSailingGroup() {
return sailingGroup;
}
And you may also need to add #XmlType to SailingGroup.
Are you sure that JAXB is producing the sailingGroupResponse tag? When I run the following stripped down example I get reasonable XML:
XML Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<sailingGroup/>
<sailingGroup/>
</root>
Demo Code
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
public class Demo {
public static void main(String[] args) throws Exception {
SailingAvailabilityResponseMessage sarm = new SailingAvailabilityResponseMessage();
SailingGroupResponse[] sgr = new SailingGroupResponse[2];
sgr[0] = new SailingGroupResponse();
sgr[1] = new SailingGroupResponse();
sarm.setSailingGroup(sgr);
JAXBElement<SailingAvailabilityResponseMessage> rootElement = new JAXBElement<SailingAvailabilityResponseMessage>(new QName("root"), SailingAvailabilityResponseMessage.class, sarm);
JAXBContext jc = JAXBContext.newInstance(SailingAvailabilityResponseMessage.class, SailingGroup.class, SailingGroupResponse.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(rootElement, System.out);
}
}
SailingAvailabilityResponseMessage
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
#XmlType(propOrder = { "type", "sailingGroup"})
public class SailingAvailabilityResponseMessage {
private SailingGroupResponse[] sailingGroup;
String type;
public SailingGroupResponse[] getSailingGroup() {
return sailingGroup;
}
public void setSailingGroup(SailingGroupResponse[] sailingGroup) {
this.sailingGroup = sailingGroup;
}
#XmlAttribute
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
SalingGroupResponse
public class SailingGroupResponse extends SailingGroup {
}
SailingGroup
public class SailingGroup {
}