Rehan Rehan - 1 year ago 83
JSON Question

Converting JAXBElement<String> to json using Jackson

Have a class as follows-

public class Org{
@XmlElementRef(name = "InstitutionCode", namespace = "", type = JAXBElement.class, required = false)
protected JAXBElement<String> institutionCode;

Using Jackson converting the object org to JSON

ObjectMapper mapper = new ObjectMapper();
JAXBElement<String> code =
new JAXBElement<String>(new QName("", "institutionCode"), String.class, "inst");
Organization org = new Organization();


String jsonInString = mapper.writeValueAsString(org);

get the value as


How to get the value as



Answer Source

You could write a custom Jackson serializer for it:

public class OrgSerializer extends JsonSerializer<Org> {
    public void serialize(Org org, JsonGenerator jgen, SerializerProvider provider) 
            throws IOException, JsonProcessingException {
        jgen.writeStringField("institutionCode", org.getInstitutionCode());

Then, you can annotate the class to use the serializer:

@JsonSerialize(using = OrgSerializer.class)
public class Org {
    // ...

Or if you don't want this every time, or you can't change the class, you can pass the class as a parameter to the ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Org.class, new OrgSerializer());

Another solution coud be using @JsonView, but I haven't used that myself.