簡體   English   中英

用Jackson序列化數組

[英]Serializing array with Jackson

我正在序列化以下模型:

class Foo {

    private List<String> fooElements;
}

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

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

我怎么能讓它看起來像這樣:

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

我通過添加自定義序列化器來實現它:

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

如果你正在使用傑克遜,那么以下簡單的例子對我有用。

定義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”:[ “一”, “二”, “三”]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM