How to convert ArrayList<String> to JSON object using Jackson in Spring @ResponseBody
10,149
Solution 1
The easiest thing to is to make your controller method return a structure that maps exactly to the JSON you want - for example a List<SomeObject>
where SomeObject
is a class with a String id
field.
Solution 2
Th way of doing this is converting you List of String into a New Map.
Code :
@ResponseBody
@RequestMapping("/mapping")
function mySpring()
{
List<String> myStringList;
Map<String,String> jsonMap= new LinkedHashMap<String,String>();
// Use LinkedHashMap if you want to maintain order
String key="id";
// Id or Name
for (String myString: myStringList)
{
jsonMap.put(key,myString);
}
return jsonMap;
}
Author by
Dreamer
Updated on June 05, 2022Comments
-
Dreamer almost 2 years
Server layer will return a list of String value, like
{"Bob", "Charlotte", "Johnson", "David"...}
Now we need the List String to be a Json object to push to front end, like
[{id: "Bob"}, {id: "Charlotte"}, {id: "Johnson"}, {id: "David"...}]
or
[{name: "Bob"}, {name: "Charlotte"}, {name: "Johnson"}, {name: "David"...}]
Any label is fine, we just need a label to make it as JSON object. Does Jackson has something to convert List of String by default
i.e. {string: "Bob"}
? That will be really sweet...... -
Dreamer almost 11 yearsThank you. Like you said I made an inner class with only one String field to hold the value, then made a list of this class object. Now it can be identified from front end.