There's no built-in way to do this. You'll have to write your own JsonSerializer. Something like
class ModelSerializer extends JsonSerializer<List<Model>> {
@Override
public void serialize(List<Model> value, JsonGenerator jgen,
SerializerProvider provider) throws IOException {
jgen.writeStartArray();
for (Model model : value) {
jgen.writeStartObject();
jgen.writeObjectField("model", model);
jgen.writeEndObject();
}
jgen.writeEndArray();
}
}
and then annotate the models field so that it uses it
@JsonSerialize(using = ModelSerializer.class)
private List<Model> models;
This would serialize as
{
"status": "success",
"models": [
{
"model": {
"id": 1,
"color": "red"
}
},
{
"model": {
"id": 2,
"color": "green"
}
}
]
}
If you're both serializing and deserializing this, you'll need a custom deserializer as well.
Answer from Sotirios Delimanolis on Stack OverflowThere's no built-in way to do this. You'll have to write your own JsonSerializer. Something like
class ModelSerializer extends JsonSerializer<List<Model>> {
@Override
public void serialize(List<Model> value, JsonGenerator jgen,
SerializerProvider provider) throws IOException {
jgen.writeStartArray();
for (Model model : value) {
jgen.writeStartObject();
jgen.writeObjectField("model", model);
jgen.writeEndObject();
}
jgen.writeEndArray();
}
}
and then annotate the models field so that it uses it
@JsonSerialize(using = ModelSerializer.class)
private List<Model> models;
This would serialize as
{
"status": "success",
"models": [
{
"model": {
"id": 1,
"color": "red"
}
},
{
"model": {
"id": 2,
"color": "green"
}
}
]
}
If you're both serializing and deserializing this, you'll need a custom deserializer as well.
This is an oldish question, But there is an arguably more idiomatic way of implementing this (I'm using jackson-databind:2.8.8):
Define a ModelSerializer (That extends StdSerializer as recommended by Jackson) that prints your model how you like and use the @JsonSerialize(contentUsing = ...) over your collection type:
class ModelSerializer extends StdSerializer<Model> {
public ModelSerializer(){this(null);}
public ModelSerializer(Class<Model> t){super(t);} // sets `handledType` to the provided class
@Override
public void serialize(List<Model> value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
jgen.writeObjectField("model", value);
jgen.writeEndObject();
}
}
Meanwhile, in another file:
class SomethingWithModels {
// ...
@JsonSerialize(contentUsing = ModelSerializer.class)
private Collection<Model> models;
// ...
}
Now you aren't bound to just Lists of models but may apply this to Collections, Sets, Native []s and even the values of Maps.
java - How to serialize Object to JSON? - Stack Overflow
java - How to serialize objects to json? - Stack Overflow
How to convert List to Json in Java - Stack Overflow
java - How to serialize object to json with Jackson, including ArrayList - Stack Overflow
Found a SerializationFeature WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED by which we can obtain the above mentioned scenario in JSON
Is this what you are looking for?
String json = mapper.writeValueAsString(!CollectionUtils.isEmpty(testObject) && testObject.size()==1? testObject.get(0):testObject);
Easy way to do it without annotations is to use Gson library
Simple as that:
Gson gson = new Gson();
String json = gson.toJson(listaDePontos);
One can use the Jackson library as well.
Add Maven Dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
Simply do this:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString( serializableObject );
To easily serialize objects to json in Java, I suggest using the GSON library.
Gson gson = new Gson();
gson.toJson(events);
You can then turn this back to a Java object with
List<Event> events = gson.fromJson(string, Event.class);
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
Serializing objects to Json in Java and back can be done as follows:
import com.fasterxml.jackson.databind.ObjectMapper;
...
Event event; // event should be instantiated (must not be null)
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(event);
Event event2 = objectMapper.readValue(json, Event.class); // event and event2 are equal
Use GSON library for that. Here is the sample code
List<String> foo = new ArrayList<String>();
foo.add("A");
foo.add("B");
foo.add("C");
String json = new Gson().toJson(foo );
Here is the maven dependency for Gson
<dependencies>
<!-- Gson: Java to Json conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
Or you can directly download jar from here and put it in your class path
http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q=
To send Json to client you can use spring or in simple servlet add this code
response.getWriter().write(json);
You need an external library for this.
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google GSON is one of such libraries
You can also take a look here for examples on converting Java object collection to JSON string.