OVB
OVB

Reputation: 227

Convert XML key value mapping to JSON object

I currently have an object which is a key-value pair that I have converted from XSD to POJO using JAXB and I tried using Jackson 2.x to get the JSON output for the POJO. This JSON output looks like:

[ { "key" : "key1", "value" : 1 }, { "key" : "key2", "value" : "2" }, { "key" : "key3", "value" : [ ] } ]

Currently my XSD generated POJO looks like:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MapEntryType", propOrder = {
"value"
})
public class MapEntryType {
    @XmlElement(required = true)
    protected Object value;
    @XmlAttribute(name = "key", required = true)
    protected String key;
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "mapEntries"
})
@XmlRootElement(name = "EventsSearchResponse")
public class EventsSearchResponse {
    @XmlElement(name = "MapEntry")
    protected List<MapEntryType> mapEntries;
}

I would like to generate the map as a simple JSON object:

{ "key1" : 1, "key2" : "2", "key3" : []}

I went over the annotations that are available in Jackson from http://wiki.fasterxml.com/JacksonAnnotations but I have not been able to find a way to perform this type of conversion. Any help regarding this would be really appreciated! Thanks.

Upvotes: 0

Views: 1381

Answers (1)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14383

I was able to achieve the desired results with a custom serializer (written as inner class for convinience):

public static class EventsSearchResponseSerializer extends JsonSerializer<EventsSearchResponse>
{
    @Override
    public void serialize(EventsSearchResponse res, JsonGenerator gen, SerializerProvider serializers)
            throws IOException, JsonProcessingException
    {
        gen.writeStartObject();

        for (MapEntryType t : res.mapEntries) {
            gen.writeObjectField(t.key, t.value);
        }
        gen.writeEndObject();
    }
}

added the proper annotation to the POJO:

@JsonSerialize(using = EventsSearchResponseSerializer.class)
@XmlRootElement(name = "EventsSearchResponse")
public static class EventsSearchResponse {
    @XmlElement(name = "MapEntry")
    public List<MapEntryType> mapEntries; 
}

calling the Jackson mapper:

public static void main(String[] args)
{
    EventsSearchResponse r = new EventsSearchResponse();
    r.mapEntries = new ArrayList<>();
    MapEntryType t = new MapEntryType();
    t.key = "key1";
    t.value = new Integer(1);
    r.mapEntries.add(t);
    t = new MapEntryType();
    t.key = "key2";
    t.value = new Integer(2);
    r.mapEntries.add(t);
    t = new MapEntryType();
    t.key = "key2";
    t.value = new String[0];
    r.mapEntries.add(t);

    try {
        System.out.println(new ObjectMapper().writeValueAsString(r));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

gives result:

{"key1":1,"key2":2,"key2":[]}

Upvotes: 1

Related Questions