JaxbDto Serialization and deserialization

Tags: , , , ,



I need to receive some message with SOAP so I’ve generated a few classes by xsd-scheme and maven-jaxb2-plugin like this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Claim", propOrder = {
    "field",
})
public class ClaimType {

    @XmlElement(required = true, type = Integer.class, nillable = false)
    protected Integer field;

    public Integer getField() {
        return bpType;
    }

    public void setField(Integer value) {
        this.field= value;
    }

}

After receiving message I need to send these to the next one microservice in wrap of HashMap. I supposed to use ObjectMapper to convert:

//JAXB DTO --> JSON
ObjectMapper objectMapper = new ObjectMapper();
String jsonContent = objectMapper.writeValueAsString(claimType);
map.put("json", jsonContent);

//JSON --> JAXB DTO
ObjectMapper objectMapper = new ObjectMapper();
String json = map.get("json");
ClaimType claimType = objectMapper.readValue(json, ClaimType.class);

But the generated classes are haven’t any constructors so I got the exception like “

No creator like default constructor are exists”.

What is the best preactice to work with Jaxb Dto? Can I do smth to successful convert these json to object? Thanks in advance!

Answer

I’ve solved my problem by using ObjectMapper MixIn:

import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;

@JsonIgnoreProperties(value = {"globalScope", "typeSubstituted", "nil"})
public abstract class JAXBElementMixIn<T> {

    @JsonCreator
    public JAXBElementMixIn(@JsonProperty("name") QName name,
            @JsonProperty("declaredType") Class<T> declaredType,
            @JsonProperty("scope") Class scope,
            @JsonProperty("value") T value) {
    }
}

And the convertation:

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.addMixIn(JAXBElement.class, JAXBElementMixIn.class);

solution link



Source: stackoverflow