Using Kotlin to convert a map collection to a JSON array using Jackson

Recently started learning Kotlin, I'm attempting to configure a web server using the kotlin spring webserver template

I need assistance with converting a kotlin collection into an array of JSON objects

The endpoint is called test

@PostMapping(value = [ "/test"],produces = [ "application/json" ],headers = [ "Content-Type=application/json" ])
    fun test(@RequestBody request:IOUDATA): ResponseEntity<String>{

      //I want this as a JSON array of objects
      val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)

      return ResponseEntity.status(HttpStatus.CREATED).body("${numbersMap}");

}

Desired output

 {
   result:[
     {"key1":1},{"key2":2}...
    ]
   }

Answer №1

The problem lies in your controller's return type being specified as a String, leading Jackson to not handle the serialization. Instead, it resorts to using Kotlin's default toString method through string interpolation.

To address this issue and have Jackson serialize the object correctly, you can opt for one of two approaches:

  1. Modify the controller to return a ResponseEntity<String> and manually serialize the object to form a String:

    @RestController
    class MyController(private val objectMapper: ObjectMapper) {
    
        @PostMapping(value = ["/test"], produces = ["application/json"], headers = ["Content-Type=application/json"])
        fun test(@RequestBody request: MyInputData): ResponseEntity<String> {
    
            val numbersMap = mapOf(
                "result" to listOf(
                    mapOf("key1" to 1),
                    mapOf("key2" to 2),
                    mapOf("key3" to 3),
                    mapOf("key4" to 1)
                )
            )
            val mySerialisedString = objectMapper.writeValueAsString(numbersMap)
    
            return ResponseEntity.status(HttpStatus.CREATED).body(mySerialisedString) // Automatic serialization by Jackson
    
        }
    }
    

    Remember that in this scenario, you'll need to acquire an instance of ObjectMapper (autowired by Spring).

  2. Create a custom result object that Jackson will automatically serialize (leveraged by Spring behind the scenes):

    @RestController
    class MyController {
    
        @PostMapping(value = ["/test"], produces = ["application/json"], headers = ["Content-Type=application/json"])
        fun test(@RequestBody request: MyInputData): ResponseEntity<MyOutputData> {
    
            val numbersMap = listOf(mapOf("key1" to 1), mapOf("key2" to 2), mapOf("key3" to 3), mapOf("key4" to 1))
    
            val myOutputData = MyOutputData(numbersMap)
            return ResponseEntity.status(HttpStatus.CREATED).body(myOutputData) // Automatic serialization by Jackson
    
        }
    }
    
    class MyOutputData(val result: List<Map<String, Int>>)
    

Both methods will generate the same JSON response upon invocation:

{
    "result": [
    {
        "key1": 1
    },
    {
        "key2": 2
    },
    {
        "key3": 3
    },
    {
        "key4": 1
    }
    ]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

MVC3: Easily browse through tables by accessing details directly from the details view, eliminating the need to click on

I am currently working on an Index view where a table displays a list of items, each with a link to show its details in another partialview loaded through Ajax. Users have expressed interest in being able to easily navigate between "Next Item" and "Previo ...

Encountered an error while compiling following the 'npm start' command in the create-react-kotlin

Having an issue running the create-react-kotlin-app module using npm. Here's the error I'm encountering: Failed to compile multi ./node_modules/react-dev-utils/webpackHotDevClient.js ./node_modules/react-scripts-kotlin/config/polyfills.js kot ...

Enhancing WebAPI service with batch request capabilities

My Batch WebAPI and WebAPI service have been registered in the webapiconfig.cs file with the following code: config.Routes.MapHttpBatchRoute( routeName: "WebApiBatch", routeTemplate: "api/$batch", batchHandl ...

Utilizing Powershell to eliminate characters from a string

After pulling a list of IPs from a JSON file, I've been using the code snippet below: $Request = 'https://url-to-json.com/file.json' $AWSIPs = Invoke-WebRequest $Request | ConvertFrom-Json | Select-Object prefix -ExpandProperty prefixes -Ex ...

Export a SQLite table with a JSON column without the need for double escaping characters

Consider a SQLite table created as follows: create table t(id, j json); insert into t values (1, '{"name": "bob"}'); insert into t values (2, '{"name": "alice", "age":20, "hobbies": ...

The Laravel model's attribute appears as empty in the JSON response

In my Laravel 4.2 project, I have a model with a 'status' attribute and declared an accessor to handle it: public function getStatusAttribute($status) { if (isset($this->expires_at) && strtotime(\Carbon\Carbon::now()) > ...

Deleting occurrences of a specific text from a JSON document and subsequently analyzing its contents

I am having an issue with a JSON file in which there are strings of characters attached to many of the field names. This is making it difficult for me to target those objects in JS. The structure looks like this: "bk:ParentField": { "bk:Field": "Va ...

How to use AJAX to dynamically populate an HTML form with data retrieved from a PHP query结果

I'm having trouble populating a form with values after running a simple search. When I execute the script, I either receive an "undefined" response or nothing at all when I try alert(data);. search.php <?php include_once 'config/config.php&a ...

Adding user inputs to the tail end of API requests in Python

def i(bot,update,args): coin=args infoCall =requests.get("https://api.coingecko.com/api/v3/coins/").json() coinId = infoCall ['categories'] update.message.reply_text(coinId) An issue arises when trying to include the args specifi ...

Expanding JSON response with additional properties through the utilization of the jQuery File-Upload plugin within the Struts 2 framework

I am currently utilizing the jQuery File-Upload plugin in conjunction with Struts 2. Within my action, I am populating the JSON object "results". This is the only information I wish for my action to return. However, the plugin is also including ...

What is the best way to determine if the properties in a JSON file are arranged in a specific

I have a large JSON file that is frequently updated with translation values. I am looking to verify if the properties in this JSON are sorted alphabetically. Ideally, I would like to automate this task using gulp and run it in a continuous integration envi ...

How do I retrieve a specific value from the JSON response using JSONObject?

I have a response with important values that I need to extract. private void getDataFromDistanceMatrixToSaveAndAddToList( GRATestDataImport place, String response) { JSONObject responseAsJson = new JSONObject(response).getJSONArray("rows&q ...

Learn how to effortlessly update models by integrating AngularJS with Django and Django Rest Framework

Here is a JSON representation of a post based on its ID: http://127.0.0.1:8000/update/1?format=json {"title": "about me", "content": "I like program", "created": "2014-11-29T18:07:18.173Z", "rating": 1, "id": 1} I am attempting to update the rating ...

Download Android contact information in csv layout

Hello, I am new to Android and interested in learning how to export my contacts into a CSV format. I need to transfer the file to a web server and store it in a centralized database using MySQL. Using vCard is not my preferred method... Alternatively ...

Encountering a problematic JQuery Ajax request to a RESTful API

I am currently in the process of trying to authenticate against demo webservices that were developed by one of my colleagues. While Cross-origin resource sharing is allowed and functions perfectly when I attempt to call from the Advanced Rest Client plugin ...

From Transforming Tabular Parent-Child Data into Tree Structures

My sql table structure is similar to the one below. The rowId serves as the primary key and parentID indicates the rowID of the parent record: RowID ParentID Name 1 0 Fruit 2 1 Apple 3 1 Peach 4 0 Veggie 5 4 Corn 6 5 Sweet Corn I am look ...

Unable to observe modifications in json file within java project (jsp)

I am currently using IntelliJ IDEA to develop a web project with JSP. I retrieve data from a file called "customer.json", and when I click on a button, I update this file in the backend. However, after trying to fetch the updated data again, it still reads ...

Error encountered when accessing JSON data from the DBpedia server in JavaScript

Hello everyone and thank you for your help in advance. I have encountered this error: Uncaught SyntaxError: Unexpected identifier on line 65 (the line with the "Var query", which is the third line) and when I click on the Execute button, I get another e ...

Handling the Json response in Spring MVC after the initial processing

I have a range of controllers that utilize the @ResponseBody annotation to return a common Response object: @RequestMapping(value = "/status", method = RequestMethod.GET) @Transactional(readOnly = true) public @ResponseBody Response<StatusVM> ...

Retrieving a json file from a local server by utilizing angularjs $http.get functionality

After fetching a JSON file from localhost, I can see the data when I console log. However, when I inject the Factory into my controller, it returns a null object. This indicates that the variable errorMessage does not receive the JSON object because the ...