如何将Map <string,string>序列化为Key:Values数组

时间:2016-12-07 21:23:28

标签: java json jackson

如何序列化键 - 值对的映射,以便生成的JSON具有以下形式:

["key1":"value1", "key2":"value2", "keyN":"valueN"]

Map序列化的默认方式是:

{"key1":"value1", "key2":"value2", "keyN":"valueN"}

我尝试制作的自定义序列化程序似乎想将它们放在单独的对象中,就像我从下面的代码段中取出注释一样

public class MapToArraySerializer extends JsonSerializer<Map<String,String>>
{
    @Override
    public void serialize(Map<String,String> additionalData, JsonGenerator generator, SerializerProvider provider) throws IOException
    {
        generator.writeStartArray();
        for (String key : additionalData.keySet()) {
            //generator.writeStartObject();
            generator.writeObjectField(key, additionalData.get(key));
            //generator.writeEndObject();
        }
        generator.writeEndArray();
    }
}

我得到以下内容:

com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value
    at com.fasterxml.jackson.core.JsonGenerator._reportError(JsonGenerator.java:1886)
    at com.fasterxml.jackson.core.json.WriterBasedJsonGenerator.writeFieldName(WriterBasedJsonGenerator.java:126)
    at com.fasterxml.jackson.core.JsonGenerator.writeObjectField(JsonGenerator.java:1651)

1 个答案:

答案 0 :(得分:0)

正如@Henrik指出的那样,这是无效的,但我能够通过使用@JsonRawValue注释来实现这一点:

@JsonRawValue
public String getAdditionalData()
{
    String json = "[";
    List<String> keys = new ArrayList<>(additionalData.keySet());
    for (int i = 0; i < keys.size(); i++) {
        String key = keys.get(i);
        json = json + "\"" + key + "\":\"" + additionalData.get(key) + "\"";
        if (i + 1 < keys.size()) {
            json = json + ",";
        }
    }
    return json + "]";
}