11

我正在序列化以下模型:

class Foo {

    private List<String> fooElements;
}

如果fooElements包含字符串“一”、“二”和“三”。JSON 包含一个字符串:

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

我怎样才能让它看起来像这样:

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

2 回答 2

14

我通过添加自定义序列化程序使其工作:

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();
    }
}
于 2013-09-05T20:48:21.117 回答
8

如果您使用的是 Jackson,那么下面的简单示例对我有用。

定义 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":["one","two","three"]}

于 2013-09-05T14:00:36.500 回答