Reputation: 5645
I'm serializing the following model:
class Foo {
private List<String> fooElements;
}
If fooElements
contains the strings 'one', 'two' and 'three. The JSON contains one string:
{
"fooElements":[
"one, two, three"
]
}
How can I get it to look like this:
{
"fooElements":[
"one", "two", "three"
]
}
Upvotes: 14
Views: 34227
Reputation: 1761
If you are using Jackson, then the following simple example worked for me.
Define the Foo class:
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:
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));
}
}
Output:
{"fooElements":["one","two","three"]}
Upvotes: 8
Reputation: 5645
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();
}
}
Upvotes: 15