Why are you putting your list into Map? Code looks weird. If you want to return a list, just do it:
@RequestMapping("/getGodowns")
public @ResponseBody List<CscGodownBean> getGodownsBasedOnDistrict(@RequestParam(value="district_code") String dist_code) {
List<CscGodownBean> godown_list = null;
String exception = null;
try {
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
} catch (Exception ex) {
ex.printStackTrace();
exception = ex.getMessage();
}
return godown_list;
}
Answer from Leffchik on Stack OverflowWhy are you putting your list into Map? Code looks weird. If you want to return a list, just do it:
@RequestMapping("/getGodowns")
public @ResponseBody List<CscGodownBean> getGodownsBasedOnDistrict(@RequestParam(value="district_code") String dist_code) {
List<CscGodownBean> godown_list = null;
String exception = null;
try {
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
} catch (Exception ex) {
ex.printStackTrace();
exception = ex.getMessage();
}
return godown_list;
}
Change the return result from Map to List<CscGodownBean> and put : retrun godown_list
So;
@RequestMapping("/getGodowns")
public @ResponseBody List<CscGodownBean>
getGodownsBasedOnDistrict(@RequestParam(value="district_code") String
dist_code) {
List<CscGodownBean> godown_list = new ArrayList<CscGodownBean>();
String exception = null;
try
{
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
}catch(Exception ex)
{
ex.printStackTrace();
exception = ex.getMessage();
}
return godown_list ;
}
UPDATE
And you can return result as string and you will get what you need :
@RequestMapping("/getGodowns")
public @ResponseBody String
getGodownsBasedOnDistrict(@RequestParam(value="district_code") String
dist_code) {
List<CscGodownBean> godown_list = new ArrayList<CscGodownBean>();
String exception = null;
try
{
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
}catch(Exception ex)
{
ex.printStackTrace();
exception = ex.getMessage();
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String arrayToJson = objectMapper.writeValueAsString(godown_list);
System.out.println("Convert List to JSON :");
System.out.println(arrayToJson);
return arrayToJson ;
}
The returned String is json format.
java - How to convert list of Objects to JSON in Spring MVC and Hibernate? - Stack Overflow
receiving json and deserializing as List of object at spring mvc controller - Stack Overflow
java - convert list into JSON Format in spring - Stack Overflow
How to convert a List to JSON? - Stack Overflow
Here is the code that works for me. The key is that you need a wrapper class.
public class Person {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
A PersonWrapper class
public class PersonWrapper {
private List<Person> persons;
/**
* @return the persons
*/
public List<Person> getPersons() {
return persons;
}
/**
* @param persons the persons to set
*/
public void setPersons(List<Person> persons) {
this.persons = persons;
}
}
My Controller methods
@RequestMapping(value="person", method=RequestMethod.POST,consumes="application/json",produces="application/json")
@ResponseBody
public List<String> savePerson(@RequestBody PersonWrapper wrapper) {
List<String> response = new ArrayList<String>();
for (Person person: wrapper.getPersons()){
personService.save(person);
response.add("Saved person: " + person.toString());
}
return response;
}
The request sent is json in POST
{"persons":[{"name":"shail1","age":"2"},{"name":"shail2","age":"3"}]}
And the response is
["Saved person: Person [name=shail1, age=2]","Saved person: Person [name=shail2, age=3]"]
This is not possible the way you are trying it. The Jackson unmarshalling works on the compiled java code after type erasure. So your
public @ResponseBody ModelMap setTest(@RequestBody List<TestS> refunds, ModelMap map)
is really only
public @ResponseBody ModelMap setTest(@RequestBody List refunds, ModelMap map)
(no generics in the list arg).
The default type Jackson creates when unmarshalling a List is a LinkedHashMap.
As mentioned by @Saint you can circumvent this by creating your own type for the list like so:
class TestSList extends ArrayList<TestS> { }
and then modifying your controller signature to
public @ResponseBody ModelMap setTest(@RequestBody TestSList refunds, ModelMap map) {
@ResponseBody should return a JSON object but here is what you can try:
public @ResponseBody ArrayList<YourObject>
myFunction(HttpServletResponse response) {
response.setContentType("application/json");
return yourArrayList;`
}
You can also try returning a Map instead. Keep your return type as Map <String, Object> and put your ArrayList in the map. This will also work.
Try to put your list inside an object like
class JSONResponse{
List<String> names;
//other nodes of JSON
}
Return the object as response You can also replace String with the objects you desire. Please post the code if you need clear help.
Try to add @ResponseBody in method declaration:
public @ResponseBody List getClients()
I've found the solution using @ResponseBody in my controller as @vacuum commented (thanks!):
@RequestMapping(method = RequestMethod.GET, value = "/clients")
public @ResponseBody List getClients(
@RequestParam(value = "estat", required = false) String estat
throws Exception {
List<Clients> l = s.mdClients(estat);
return l;
}
I also needed to change my output-conversion method, using
<mvc:annotation-driven />
in my servlet-context.xml, in order to use jackson library for the json conversion of my list.
The output now:
[
{
"x": "2",
"y": "5"
}
]
My project uses spring data embers for auditing and I would like users to be able to see the data in the auditing table using a controller endpoint. So something like “/audit/2” would give produce a JSON array with the auditing history of the model object that has an id of 2.
My repository class extends RevisionRepository and gives me some methods I can work with like findRevisions(id).
My question is how do I convert the output of this method (which is a Revision object) into a JSON array? Do I need a DTO to manually get its fields from the Revision object or is there an easier way?
The JSON response you are getting is invalid - I recommend validate JSON using - [JSON Formatter]
Here is the code for your solution, Change siteInfo[i].cardName with whatever value you want to use e.g. cardName, id... (i used cardName in below code).
Enjoy! :)
var siteInfo =
[
{
"createdAt": "2021-08-21T05:04:45.000+00:00",
"updatedAt": "2021-08-21T05:04:45.000+00:00",
"id": 1,
"cardName": "Demon Fiend"
},
{
"createdAt": "2021-08-21T05:04:58.000+00:00",
"updatedAt": "2021-08-21T05:04:58.000+00:00",
"id": 2,
"cardName": "Stack"
},
{
"createdAt": "2021-08-21T05:05:00.000+00:00",
"updatedAt": "2021-08-21T05:05:00.000+00:00",
"id": 3,
"cardName": "Overflow"
}
]
var map = new Map();
for(var i=0; i<siteInfo.length; i++) {
map.set(siteInfo[i].cardName, siteInfo[i]);
}
let jsonObject = {};
map.forEach((value, key) => {
jsonObject[key] = value
});
console.log(JSON.stringify(jsonObject));
I must confess your question is bit confusing to me.
I am assuming that you are returning a list of objects in your controller as the response. Like this,
public List<YourDtoClass> ...
If that's the case what you can do is return a Map instead. Like this,
public Map<String, YourDtoClass>
If you already created a List, you can crate Map as follows,
return yourList.stream().collect(Collectors.toMap(YourDtoClass::getCardName, Function.identity()));