用Jackson序列化数组

时间:2013-09-04 20:59:20

标签: java serialization jackson

我正在序列化以下模型:

class Foo {

    private List<String> fooElements;
}

如果fooElements包含字符串'one','two'和'three。 JSON包含一个字符串:

{
    "fooElements":[
         "one, two, three"
     ]
}

如何让它看起来像这样:

{
    "fooElements":[
         "one", "two", "three"
     ]
}

2 个答案:

答案 0 :(得分:9)

我通过添加自定义序列化器来实现它:

class Foo {
    @JsonSerialize(using = MySerializer.class)
    private List<String> fooElements;
}

public class MySerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonProcessingException {
        List<String> fooList = (List<String>) value;

        if (fooList.isEmpty()) {
            return;
        }

        String fooValue = fooList.get(0);
        String[] fooElements = fooValue.split(",");

        jgen.writeStartArray();
        for (String fooValue : fooElements) {
            jgen.writeString(fooValue);
        }
        jgen.writeEndArray();
    }
}

答案 1 :(得分:8)

如果你正在使用杰克逊,那么以下简单的例子对我有用。

定义Foo类:

public class Foo {
    private List<String> fooElements = Arrays.asList("one", "two", "three");

    public Foo() {
    }

    public List<String> getFooElements() {
        return fooElements;
    }
}

然后使用独立的Java应用程序:

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonExample {

    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {

        Foo foo = new Foo();

        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(foo));

    }

}

输出:

  

{ “fooElements”:[ “一”, “二”, “三”]}