Duplicate values in the output of ObjectMapper.writeValueAsString - java

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

Related

Jackson Cannot Find a (Map) Key Deserializer for Path?

I have a strange issue where I have a HashMap that I serialize for later use on the disk.
It is a HashMap<Path, ConverterMetadata> the ConverterMetadata being a custom class that I wrote to keep track of music file metadata.
The ConverterMetadata appears to have proper tags and in my testing I have confirmed that Jackson can write and read Map<Path, String> instances, so I'm not entirely sure what is happening here, and why it says that it is breaking on the key (Path) object.
Here is the exception, the class, the JSON outputted, and the method that reads/writes it:
The Exception:
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot find a (Map) Key deserializer for type [simple type, class java.nio.file.Path]
at [Source: (File); line: 1, column: 1]
at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452)
at com.fasterxml.jackson.databind.deser.DeserializerCache._handleUnknownKeyDeserializer(DeserializerCache.java:599)
at com.fasterxml.jackson.databind.deser.DeserializerCache.findKeyDeserializer(DeserializerCache.java:168)
at com.fasterxml.jackson.databind.DeserializationContext.findKeyDeserializer(DeserializationContext.java:500)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.createContextual(MapDeserializer.java:248)
at com.fasterxml.jackson.databind.DeserializationContext.handleSecondaryContextualization(DeserializationContext.java:682)
at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:482)
at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:4191)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4010)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2922)
at com.protonmail.sarahszabo.stellar.conversions.SpaceBridge.initBridge(SpaceBridge.java:151)
at com.protonmail.sarahszabo.stellar.StellarMode$2.start(StellarMode.java:87)
at com.protonmail.sarahszabo.stellar.Main.stellarConversion(Main.java:203)
at com.protonmail.sarahszabo.stellar.Main.main(Main.java:77)
ConverterMetadata Class:
/**
* A representation of .opus metadata. Used in concordance with a
* {#link StellarOPUSConverter}. All fields are immutable.
*/
public final class ConverterMetadata {
/**
* The default metadata instance.
*/
public static final ConverterMetadata DEFAULT_METADATA = new ConverterMetadata("Unknown Artist",
"Unknown Title", Main.FULL_PROGRAM_NAME, LocalDate.MAX, StellarGravitonField.newPath(""), Integer.MAX_VALUE);
#JsonProperty
private final String artist;
#JsonProperty
private final String title;
#JsonProperty
private final String createdBy;
#JsonProperty
private final LocalDate stellarIndexDate;
#JsonProperty
private final Path albumArtPath;
#JsonProperty
private final int bitrate;
/**
* Constructs a new {#link ConverterMetadata} with the specified arguments.
*
*
* #param artist The artist for this track
* #param title The title of this track
* #param createdBy The program that created this track/last modified this
* track
* #param date The date this track was created
* #param albumArtPath The path to the album art
* #param bitrate The bitrate of the track
*/
#JsonCreator
public ConverterMetadata(#JsonProperty(value = "artist") String artist,
#JsonProperty(value = "title") String title, #JsonProperty(value = "createdBy") String createdBy,
#JsonProperty(value = "stellarIndexDate") LocalDate date, #JsonProperty(value = "albumArtPath") Path albumArtPath,
#JsonProperty(value = "bitrate") int bitrate) {
//Do Consructor Stuff Here
}
}
Code that Writes/Reads from the Ledger File AKA initBridge():
Map<Path, ConverterMetadata> LIBRARY_LEDGER = new HashMap<>();
//Earlier in the code, write ledger, to disk
MAPPER.writeValue(LIBRARY_LEDGER_PATH.toFile(), LIBRARY_LEDGER);
//Later we read the ledger
Map<Path, ConverterMetadata> previousLedger = MAPPER.readValue(LIBRARY_LEDGER_PATH.toFile(),
new TypeReference<HashMap<Path, ConverterMetadata>>() {
});
LIBRARY_LEDGER.putAll(previousLedger);
JSON in the File:
{"/home/sarah/Music/Indexing/Playlists/Best Playlist/Spiral.opus":{"artist":"Vangelis","title":"Spiral","createdBy":"Stellar OPUS Conversion Library 1.4α","stellarIndexDate":[2018,7,23],"albumArtPath":"file:///tmp/Stellar%20OPUS%20Converter%20Temporary%20Directory15723231348656772389/ReIndexing/Spiral.png","bitrate":320},"/home/sarah/Music/Indexing/Playlists/Finished/Aphelion.opus":{"artist":"Scandroid","title":"Aphelion","createdBy":"Stellar OPUS Conversion Library 1.4α","stellarIndexDate":[2018,8,8],"albumArtPath":"file:///tmp/Stellar%20OPUS%20Converter%20Temporary%20Directory15723231348656772389/ReIndexing/Aphelion.png","bitrate":320}
POM:
<properties>
...
<!-- Use the latest version whenever possible. -->
<jackson.version>2.9.8</jackson.version>
...
</properties>
<dependencies>
...
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
...
</dependencies>
You need to implement key deserialiser for java.nio.file.Path class. It could like below:
class PathKeyDeserializer extends KeyDeserializer {
#Override
public Object deserializeKey(String key, DeserializationContext ctxt) {
return Paths.get(key);
}
}
You can register it and use like in below example:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class JsonApp {
public static void main(String[] args) throws Exception {
Map<Path, String> path2String = new HashMap<>();
path2String.put(Paths.get("user", "downloads"), "Downloads");
path2String.put(Paths.get("home", "des"), "Desktop");
SimpleModule nioModule = new SimpleModule();
nioModule.addKeyDeserializer(Path.class, new PathKeyDeserializer());
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.registerModule(nioModule);
String json = mapper.writeValueAsString(path2String);
System.out.println(json);
path2String = mapper.readValue(json, new TypeReference<HashMap<Path, String>>() {});
System.out.println(path2String);
}
}
Above code prints:
{
"home/des" : "Desktop",
"user/downloads" : "Downloads"
}
{home/des=Desktop, user/downloads=Downloads}

override #XmlElement annotation with FIELD accessor type

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

Array Serialize Gives Qualified Class name using Jackson

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)

How to use Jackson's JaxbAnnotationIntrospector correctly?

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.

Java/XML problem

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

Categories

Resources