Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating JSON using Jackson

Tags:

java

json

jackson

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

like image 283
braincell Avatar asked Jul 19 '26 04:07

braincell


1 Answers

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.

like image 167
alex.p Avatar answered Jul 20 '26 19:07

alex.p