将XML键值映射转换为JSON对象

时间:2015-11-16 23:41:01

标签: java json jackson

我目前有一个对象,它是一个键值对,我已经使用JAXB从XSD转换为POJO,我尝试使用Jackson 2.x来获取POJO的JSON输出。此JSON输出如下所示:

[{   “key”:“key1”,   “价值”:1 },{   “key”:“key2”,   “价值”:“2” },{   “key”:“key3”,   “价值”:[] }]

目前我的XSD生成POJO如下:

@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;
}

我想将地图生成为一个简单的JSON对象:

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

我从http://wiki.fasterxml.com/JacksonAnnotations查看了杰克逊提供的注释,但我无法找到执行此类转换的方法。任何有关这方面的帮助将非常感谢!感谢。

1 个答案:

答案 0 :(得分:1)

我能够使用自定义序列化程序(为了方便而编写为内部类)来实现所需的结果:

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

在POJO中添加了正确的注释:

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

致电杰克逊映射器:

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

给出结果:

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