Rehan Rehan - 6 months ago 37
JSON Question

Converting JAXBElement<String> to json using Jackson

Have a class as follows-

public class Org{
@XmlElementRef(name = "InstitutionCode", namespace = "http://schemas.tes.org/2004/07/ABC.test", 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("http://schemas.tes.org/2004/07/ABC.test", "institutionCode"), String.class, "inst");
Organization org = new Organization();

org.setInstitutionCode(code);

String jsonInString = mapper.writeValueAsString(org);
System.out.println(jsonInString);


get the value as

{"institutionCode":{"Name":"{http://schemas.tes.org/2004/07/ABC.test}institutionCode"}


How to get the value as

{"institutionCode":"inst"}


Thanks,

Answer

You could write a custom Jackson serializer for it:

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

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());
mapper.registerModule(module);

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