This does NOT require custom serializers but simple annotation:
@JsonFormat(shape=JsonFormat.Shape.ARRAY)
public class UserModel {
// ...
}
Answer from StaxMan on Stack OverflowThis does NOT require custom serializers but simple annotation:
@JsonFormat(shape=JsonFormat.Shape.ARRAY)
public class UserModel {
// ...
}
Your scheme is fairly custom, so you'll have to do via custom serializer thing.
Please also note that I would suggest you to revise it as adding / removing new field / changing order would be much trickier in this case especially if you can't release both client and server simultaneously.
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();
}
}
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"]}
java - spring api - jackson serialize an object to an array - Stack Overflow
spring - Custom serializer for Object array using jackson - Stack Overflow
Serialization Of Polymorphic Array Failing
java - Jackson JSON: Serialize Array of Objects as their parent type - Stack Overflow
First create a mapper :
import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();
As Array:
MyClass[] myObjects = mapper.readValue(json, MyClass[].class);
As List:
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
Another way to specify the List type:
List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
From Eugene Tskhovrebov
List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))
This solution seems to be the best for me.