Reputation: 562
I have a List<Person>
list.
I want to serialize it to JSON with some other attributes, using Jackson Api.
The output should be like this:
{
"sEcho": 3,
"iTotalRecords": 10,
"iTotalDisplayRecords": 10,
"aaData": [ <--here's the persons
{
"name": "TestName1",
"status": "ok"
},
{
"name": "TestName2",
"status": "ok"
},
...
]
}
Probably very simple but couldn't figure it from Jackson's Api. Thanks
Upvotes: 3
Views: 4119
Reputation: 5946
Try with this. Hope it would help.
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonSimpleExample {
public static void main(String[] args) {
List<Person> personList = new ArrayList<Person>();
for(int i=0 ;i< 5;i ++) {
Person person = new Person("TestName" + (i+1), "OK");
personList.add(person);
}
JSONObject obj = new JSONObject();
obj.put("sEcho", 3);
obj.put("iTotalRecords", 10);
obj.put("iTotalDisplayRecords", 10);
JSONArray list = new JSONArray();
for (Person person : personList) {
JSONObject innerObj = new JSONObject();
innerObj.put("name",person.getName());
innerObj.put("status",person.getStatus());
list.add(innerObj);
}
obj.put("aaData", list);
System.out.print(obj);
}
}
class Person {
private String name;
private String status;
public Person(String name, String status) {
this.name = name;
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Upvotes: 0
Reputation: 2739
I'd create a new class called PersonGroup having any of the extra fields you need with the List as another field on this class - for the example you gave this field would be named aaData.
This would represent the structure you have here. If you think a new class is too much then you could just make a HashMap of Objects and store the extra fields as whatever object you like and then add these to the HashMap, making sure the keys match the name of the extra fields and making sure your List is also in the HashMap.
Deserializing this class or HashMap should return the output you mentioned.
Upvotes: 3