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 Overflow
Top answer
1 of 4
3

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;
}
2 of 4
2

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.

🌐
Learningprogramming
learningprogramming.net › home › convert list objects to/from json in spring rest api and spring data jpa
Convert List Objects to/from JSON in Spring Rest API and Spring Data JPA - Learn Programming with Real Apps
January 8, 2019 - package demo.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import demo.entities.Product; import demo.repositories.ProductRepository; @Service("productService") @Transactional public class ProductServiceImpl implements ProductService { @Autowired private ProductRepository productRepository; @Override public Iterable<Product> findAll() { return productRepository.findAll(); } } Create Rest API Controller provides application/json data for the client
Discussions

java - How to convert list of Objects to JSON in Spring MVC and Hibernate? - Stack Overflow
I'm Using Spring MVC and hibernate to fetch data from MySQL. In the controller class a ModelAndView method listEmployees is returning a MAP.The method is getting list of Employee objects from More on stackoverflow.com
🌐 stackoverflow.com
April 25, 2017
receiving json and deserializing as List of object at spring mvc controller - Stack Overflow
This should be the accepted answer. Take an array as the body and convert it to a list in the controller method. No need for wrapper classes or to change the format of your JSON. More on stackoverflow.com
🌐 stackoverflow.com
October 15, 2019
java - convert list into JSON Format in spring - Stack Overflow
Facing issue as not getting output as json format. ... Pair programing? We peek under the hood of Duet, Google’s coding assistant.... ... Does the policy change for AI-generated content affect users who (want to)... More on stackoverflow.com
🌐 stackoverflow.com
How to convert a List to JSON? - Stack Overflow
I am trying to display a List of items in JSON format. My code structure utilizing SpringBoot and JPA Repository on Server side: More on stackoverflow.com
🌐 stackoverflow.com
🌐
Baeldung
baeldung.com › home › spring › spring boot › get list of json objects with spring resttemplate
Get list of JSON objects with Spring RestTemplate | Baeldung
December 11, 2025 - In Spring, we can use RestTemplate to perform synchronous HTTP requests. The data is usually returned as JSON, and RestTemplate can convert it for us. In this tutorial, we’ll explore how we can convert a JSON Array into three different object structures in Java: Array of Object, Array of POJO and a List of POJO.
Top answer
1 of 6
48

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]"]
2 of 6
14

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) {
🌐
Java Guides
javaguides.net › 2019 › 07 › convert-list-to-json-array-using-jackson.html
Convert List to JSON Array Using Jackson
July 21, 2019 - In this quick article, I will show how to convert a List to JSON array using Jackson. Check out complete Jackson tutorial at Java Jackson JSON Tutorial with Examples. We are using Jackson library to convert Java List to JSON array so let's add below Jackson dependency to your project's classpath or pom.xml.
🌐
Stack Overflow
stackoverflow.com › questions › 33256443 › convert-list-into-json-format-in-spring
java - convert list into JSON Format in spring - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... How can i get json data by using criteria projection in spring MVC project. My Criteria Query as follows. public List<Item> getProduct() { Criteria crit = session.createCriteria(Item.class); ProjectionList projList = Projections.projectionList(); projList.add(Projections.property("item_code")); projList.add(Projections.property("item_name")); crit.setProjection(projList); List<Item> results = crit.list(); }
🌐
Stack Overflow
stackoverflow.com › questions › 55954621 › how-to-convert-a-list-to-json
How to convert a List to JSON? - Stack Overflow
Expected result: List of records from the database in JSON format ... There was an unexpected error (type=Internal Server Error, status=500). Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter? ... The solution was to add spring.jackson.serialization.fail-on-empty-beans=false in the application.properties file.
Find elsewhere
Top answer
1 of 1
2

It seems to me that the issue is that you are trying to pass something like the following JSON to the content:

[
  {
    "compania1_list": "Compania1 list",
    "name1": "name1",
    "s": "---",
    "s1": "---",
    "o": null,
    "o1": null
  },
  {
    "compania1_list": "Compania2 list",
    "name1": "name2",
    "s": "---",
    "s1": "---",
    "o": null,
    "o1": null
  }
]

This is a JSON Array with 2 JSON Objects and not a JSON Object with a JSON Array with 2 JSON Objects. My guess is that MockHttpServletRequestBuilder.content() method is not expecting JSON like this.

With this being said, I would change your Controller to accept an Object and not a Collection as follows:

@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/lista")
public Map<String, Object> createCompanias(@RequestBody CompaniasCreationRequest companiasCreationRequest) {
    return companiaService.postListCompanias(companiasCreationRequest.getCompanias());
}

Being CompaniasCreationRequest as follows:

public class CompaniasCreationRequest {
    private List<Compania> companias;

    public CompaniasCreationRequest(List<Compania> companias) {
        this.companias = companias;
    }

    public List<Compania> getCompanias() {
        return companias;
    }

    public void setCompanias(List<Compania> companias) {
        this.companias = companias;
    }
}

In your test this would mean the following changes:

@Test
void successSavePostCompaniaLista() throws Exception {
    Compania c1 = new Compania("Compania1 list",
        "name1",
        "---",
        "---",
        null,
        null);
    Compania c2 = new Compania("Compania2 list",
        "name2",
        "---",
        "---",
        null,
        null);

    CompaniasCreationRequest companiasCreationRequest = new CompaniasCreationRequest(List.of(c1,c2));
    
    when(companiaRepository.save(any(Compania.class))).then(returnsFirstArg());

    this.mockMvc.perform(
            post("/companias/lista")
                .header("authorization", "Bearer " + token)
                .content(asJsonString(companiasCreationRequest))
                .contentType(MediaType.APPLICATION_JSON))
        .andDo(print())
        .andExpect(status().isCreated())
        .andExpect(jsonPath("$.result[0].success[0]").isNotEmpty())
        .andExpect(jsonPath("$.result[0].success[0].name").value(c1.getName()))
        .andExpect(jsonPath("$.result[0].success[1].name").value(c2.getName()));
}

Now your request body will look like the following (which is a somewhat more standard JSON format):

{
  "companias": [
    {
      "compania1_list": "Compania1 list",
      "name1": "name1",
      "s": "---",
      "s1": "---",
      "o": null,
      "o1": null
    },
    {
      "compania1_list": "Compania2 list",
      "name1": "name2",
      "s": "---",
      "s1": "---",
      "o": null,
      "o1": null
    }
  ]
}
🌐
Quora
quora.com › How-do-I-convert-a-list-to-JSON-in-Java
How to convert a list to JSON in Java - Quora
Answer (1 of 8): Just use ObjectMapper from fasterxml library. [code]import com.fasterxml.jackson.databind.ObjectMapper; ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(anyObject); [/code]
🌐
TutorialsPoint
tutorialspoint.com › how-to-convert-a-list-to-json-array-using-the-jackson-library-in-java
How to convert a List to JSON array using the Jackson library in Java?
April 29, 2025 - <dependency> <groupid>com.fasterxml.jackson.core</groupid> <artifactid>jackson-databind</artifactid> <version>2.15.2</version> </dependency> The writeValueAsString() method of the ObjectMapper class serializes a given Java object, such as a List or ArrayList, into JSON-formatted String.
🌐
Medium
medium.com › @vino7tech › handling-json-with-objectmapper-in-spring-boot-6fc7ff39088b
Handling JSON with ObjectMapper in Spring Boot | by Vinotech | Medium
October 23, 2024 - This guide explores how to use ObjectMapper in a Spring Boot application for converting Java objects to JSON and vice versa. It covers key use cases like customizing JSON field names, handling unknown properties, working with lists, and configuring ObjectMapper for special scenarios like date formats and pretty printing.
🌐
Baeldung
baeldung.com › home › spring › spring web › get and post lists of objects with resttemplate
Get and Post Lists of Objects with RestTemplate | Baeldung
June 11, 2025 - Now let’s look at how to send a list of objects from our client to the server. Just like above, RestTemplate provides a simplified method for calling POST: postForObject(URI url, Object request, Class<T> responseType) This sends an HTTP POST to the given URI, with the optional request body, and converts the response into the specified type. Unlike the GET scenario above, we don’t have to worry about type erasure. This is because now we’re going from Java objects to JSON.
🌐
Reddit
reddit.com › r/springboot › how to convert object to json in controller?
r/SpringBoot on Reddit: How to convert object to json in controller?
September 2, 2022 -

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?