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.

๐ŸŒ
Medium
satyacodes.medium.com โ€บ springboot-export-java-objects-to-json-json-to-object-7f6d4208ed64
SpringBoot โ€” export Java Objects to JSON & JSON to Object | by Satya Kaveti | Medium
November 6, 2023 - ObjectMapper mapper = new ObjectMapper(); //Java Object -> JSON String json = mapper.writeValueAsString(employeeDto); //JSON -> Java Object EmployeeDto dto = mapper.readValue(json, EmployeeDto.class); @GetMapping("/json/export") public ResponseEntity<Resource> exportEmployeesToJson() { try { List<EmployeeDto> employees = employeeService.getAllEmployees(); String jsonData = objectMapper.writeValueAsString(employees); ByteArrayResource resource = new ByteArrayResource(jsonData.getBytes()); String fileName = "employees_" + LocalDateTime.now() + ".json"; return ResponseEntity.ok().header(HttpHeade
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
How to convert object to json in controller?
Spring will do it for you. Just create a separate controller and annotate the class with @RestController. Then just return your object or list of objects in your controller method. Spring will automatically use Jackson to serialize it to JSON. More on reddit.com
๐ŸŒ r/SpringBoot
6
6
September 2, 2022
java - Convert a object into JSON in REST service by Spring MVC - Stack Overflow
I'm trying to create a REST service using Spring MVC and it's working if I'm returning a plain string. My requirement is to return a JSON string of the Java object. Don't know how to achieve this by More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - How does Spring auto convert objects to json for @RestController - Stack Overflow
I'm looking at code in which I'm assuming spring decides to use Jackson behind the scenes to auto convert an object to json for a @RestController @RestController @RequestMapping("/api") ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
    }
  ]
}
๐ŸŒ
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
๐ŸŒ
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.
๐ŸŒ
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?

๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java list โ€บ converting a java list to a json array
Converting a Java List to a Json Array | Baeldung
June 18, 2025 - In this tutorial, we'll see how to orchestrate a multi-step flow for a ride-hailing application by integrating Dapr Workflows and Spring Boot: ... Yes, we're now running our Spring Sale. All Courses are 30% off until 31st March, 2026 ... In modern software development, the exchange of data between different systems is a common requirement. One popular data interchange format is JSON (JavaScript Object Notation). Besides, Java is a widely used programming language that provides libraries and frameworks that facilitate working with JSON data. One common task is converting a Java List to a JSON array.
Find elsewhere
๐ŸŒ
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.
๐ŸŒ
ZetCode
zetcode.com โ€บ springboot โ€บ json
Spring Boot JSON - serving JSON data in a Spring Boot annotation
July 28, 2023 - JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json. The JSON filename extension is .json. Spring Boot provides integration with three JSON mapping libraries: ... Jackson is the preferred and default library. spring.http.converters.preferred-json-mapper=jsonb
Top answer
1 of 2
1

You probably don't need custom deserializer to get this json. Just add @JsonFormat(shape = JsonFormat.Shape.OBJECT) annotation to your class:

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public static class PagedList<E> implements List<E>  {
    @JsonProperty
    private List<E> list;

    @JsonProperty // no need for this if you have getter-setters 
    private long totalRecords; 

    @JsonIgnore
    @Override
    public boolean isEmpty() {
        return false;
    }

...

Here is full demo: https://gist.github.com/varren/35c4ede769499b1290f98e39a2f85589

Update after comments:

I think Spring uses Jacksons return mapper.writerFor(List.class).writeValueAsString(new MyList()); Here is demo:

@RestController
@RequestMapping(value="/")
public static class MyRestController  {
    private static final ObjectMapper mapper = new ObjectMapper();

    //returns [] for both 0 and 1
    @RequestMapping(value="test", method = RequestMethod.GET)
    public List test(@RequestParam int user) {
        return user == 0 ? new ArrayList(): new MyList();
    }

    //returns [] for 0 and expected custom {"empty": true} for 1
    @RequestMapping(value="testObj", method = RequestMethod.GET)
    public Object testObj(@RequestParam int user) {
        return user == 0 ? new ArrayList(): new MyList();
    }

    // returns expected custom {"empty": true}
    @RequestMapping(value="testMyList", method = RequestMethod.GET)
    public MyList testMyList() {
        return new MyList();
    }

    // returns expected custom {"empty": true}
    @RequestMapping(value="testMyListMapper", method = RequestMethod.GET)
    public String testMyListMapper() throws JsonProcessingException {
        return mapper.writeValueAsString(new MyList());
    }

    // returns []
    @RequestMapping(value="testMyListMapperListWriter", method = RequestMethod.GET)
    public String testMyListMapperListWriter() throws JsonProcessingException {
        return mapper.writerFor(List.class).writeValueAsString(new MyList());
    }
}
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public static class MyList extends ArrayList {}

So you have to Option 1) return Object instead of List or Option 2) register custom serialifer for List (and not for PageList) builder.serializerByType(List.class, new PagedListSerializer()); like this:

public class PagedListSerializer extends JsonSerializer<List> {
  @Override
  public void serialize(List valueObj, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
    if (valueObj instanceof PagedList) {
      PagedList value = (PagedList) valueObj;
      gen.writeStartObject();
      gen.writeNumberField("totalRecords", value.getTotalRecords());
      gen.writeObjectField("list", value.getList());
      gen.writeEndObject();
    }else{
      gen.writeStartArray();
      for(Object obj : valueObj)
        gen.writeObject(obj);
      gen.writeEndArray();
    }
  }
}
2 of 2
0

You can Create your customObject Mapper and use your serializer there.

  <mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="custom.CustomObjectMapper"/>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
๐ŸŒ
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.
Top answer
1 of 2
4

Just return the list from the controller method

@RequestMapping(value = "/all", method = RequestMethod.GET)
@ResponseBody
public List<Object[]> getAllDeps() {
    List<Object[]> list  = departmentService.getAllDepartments();
    return list;
}

The @ResponseBody annotation does the transformation for you.

2 of 2
0
public JSONObject findOccurrByFileUUID(UUID filePefin) throws JSONException {

    StringBuilder strQuery = new StringBuilder();
    strQuery.append("SELECT c.\"name\" AS creditorname, d.\"name\" AS debtorname, concat(b2.\"type\",'-',b2.\"number\",'-',b2.parcel) AS docto, b2.uniquenumber, to_char(b.dateoccurr,'DD/MM/YYYY HH24:MI:SS') AS dateoccur, to_char(b.createddate, 'DD/MM/YYYY HH24:MI:SS') AS createddate, b.statusnegatived, l.username FROM billnegativedoccurr b \n" +
                    "LEFT JOIN billnegatived b2 ON b2.uuid = b.billnegativeduuid \n" +
                    "LEFT JOIN creditor c ON c.tenantowner_uuid = b2.tenant_uuid AND c.uuid = b2.creditor_uuid \n" +
                    "LEFT JOIN debtor d ON d.tenantowner_uuid = b2.tenant_uuid AND d.uuid = b2.debtor_uuid \n" +
                    "INNER JOIN login l ON l.uuid = b.useroccurr \n" +
                    "WHERE b.filepefinuuid = :filePefin");

    Query query = eM.createNativeQuery(strQuery.toString()); //no entity mapping
    query.setParameter("filePefin", filePefin);
    List<Object[]> queryList = query.getResultList();
    JSONArray array = new JSONArray();
    JSONObject obj = new JSONObject();

    for (Object[] result : queryList) {

        JSONObject object = new JSONObject();
        object.put("creditorName", result[0]);
        object.put("debtorName", result[1]);
        object.put("docto", result[2]);
        object.put("uniquenumber", result[3]);
        object.put("dateoccur", result[4]);
        object.put("createddate", result[5]);
        object.put("statusnegatived", result[6]);
        object.put("username", result[7]);

        array.put(object);
    }

    return obj.put("Values", array);
}
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 55954621 โ€บ how-to-convert-a-list-to-json
How to convert a List to JSON? - Stack Overflow
@Service public class InspectionService { @Autowired INSPCTNRepository inspctnRepository; @GetMapping(path="/getInspection", produces = "application/JSON") public String getInspections() { List<INSPCTN> list = inspectionService.getInspections(); Gson gson = new Gson(); String json = gson.toJson(list); return json; } }
๐ŸŒ
Moss GU
mossgreen.github.io โ€บ JSON-in-spring-boot
Returning JSON in Spring Boot - Moss GU
August 3, 2018 - @JsonProperty @JsonProperty is used to indicate the property name in JSON. public class Attribute { public int id; private String name; @JsonProperty("name") public void setTheName(String name) { this.name = name; } @JsonProperty("name") public String getTheName() { return name; } } ... public class Attribute { private Long id; private String name; @JsonProperty("options") private List<AttributeOption> attributeOptions = new ArrayList<>(); } public class AttributeOption { // some properties here }