Clay Banks
Clay Banks

Reputation: 4591

Adding Additional Attributes to a ResponseBody Object

I have the following Spring @RestController method

@RequestMapping(value = "/getPeople", method = RequestMethod.GET)
public List<Person> getPeople(Model model){
    List<People> people = personRepo.getAllPeople();
    model.addAttribute("people", people);
    return people;
}

Which returns the following to the Response Body

[
    {"name":"Jim","group":1},
    {"name":"Dwight","group":2},
    {"name":"Stanley","group":3}
]

Can I modify this method (via the @Controller method itself, or with an AJAX request) to include additional attributes, both inside or outside of the people array, and without modifying the Person object - so that the object returned could look something like

{
    "people":[
        {"name":"Jim","group":1, "independentAttribute": "A"},
        {"name":"Dwight","group":2, "independentAttribute": "B"},
        {"name":"Stanley","group":3, "independentAttribute": "C"}
    ],
    "extraAttributes":[
        {"attribute1": 1,"attribute2": 2,"attribute3":3}
    ]
}

apologies if this isn't valid object/array syntax, lackadaisically threw it together.

Upvotes: 1

Views: 2027

Answers (2)

Bnrdo
Bnrdo

Reputation: 5474

You can modify the object in the callback of the JSON request. I'm not familiar with d3_json but you can do something like

callback : function(data){
   //data is the returned List<Person> serialized to JSON
   var modifiedObj = new Object();
   modifiedObj.persons = data;
   modifiedObj.extraAttributes = [{"attribute1": 1,"attribute2": 2,"attribute3":3}]
}

Upvotes: 2

I think you are looking for a custom JSON serializer, see this link: http://www.baeldung.com/jackson-custom-serialization

Upvotes: 0

Related Questions