use*_*834 9 java serialization jackson
我正在序列化以下模型:
class Foo {
private List<String> fooElements;
}
Run Code Online (Sandbox Code Playgroud)
如果fooElements包含字符串'one','two'和'three.JSON包含一个字符串:
{
"fooElements":[
"one, two, three"
]
}
Run Code Online (Sandbox Code Playgroud)
我怎么能让它看起来像这样:
{
"fooElements":[
"one", "two", "three"
]
}
Run Code Online (Sandbox Code Playgroud)
我通过添加自定义序列化器来实现它:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
如果你正在使用杰克逊,那么以下简单的例子对我有用.
定义Foo类:
public class Foo {
private List<String> fooElements = Arrays.asList("one", "two", "three");
public Foo() {
}
public List<String> getFooElements() {
return fooElements;
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用独立的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));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
{ "fooElements":[ "一", "二", "三"]}
| 归档时间: |
|
| 查看次数: |
21154 次 |
| 最近记录: |