Java 使用 Jackson 序列化数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18623667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:36:12  来源:igfitidea点击:

Serializing array with Hymanson

javaserializationHymanson

提问by user86834

I'm serializing the following model:

我正在序列化以下模型:

class Foo {

    private List<String> fooElements;
}

If fooElementscontains the strings 'one', 'two' and 'three. The JSON contains one string:

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

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

How can I get it to look like this:

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

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

采纳答案by user86834

I got it working by adding a custom serializer:

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

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

回答by nickebbitt

If you are using Hymanson, then the following simple example worked for me.

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

Define the Foo class:

定义 Foo 类:

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

    public Foo() {
    }

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

Then using a standalone Java app:

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

import java.io.IOException;

import org.codehaus.Hymanson.JsonGenerationException;
import org.codehaus.Hymanson.map.JsonMappingException;
import org.codehaus.Hymanson.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));

    }

}

Output:

输出:

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

{"fooElements":["一","二","三"]}