1

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.

4
  • 1
    lackadaisically Fancy word. Commented Oct 12, 2015 at 21:19
  • @SotiriosDelimanolis I'm using FasterXML's JSON Processor Commented Oct 12, 2015 at 21:23
  • My mistake, it's a @RestController that returns the array to the Response Body - updated my question. Does that help? Commented Oct 12, 2015 at 21:29
  • Revised the ? again, I get the json object via an AJAX call using d3.json call (github.com/mbostock/d3/wiki/Requests#d3_json) - perhaps the object can be modified via an AJAX callback? Commented Oct 12, 2015 at 21:47

2 Answers 2

2

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}]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just what I was looking for. Thank you
0

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

4 Comments

Sorry, I don't get why you -1ed, did I misunderstand something? I thought you would like to add custom json string to the already serialized json (list of people)? Am I right?
I didn't downvote you m8. I found the answer helpful, although I've found @onepotato had what I was looking for
How would they use this JSON serializer?
Oh I see now, onepotato's solution is great, no probs :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.