Lucky Lucky - 4 months ago 117
JSON Question

How to pass multiple JSON array objects to Spring Controller?

I have created two arrays with key and values and strigified the arrays and passing both the JSON objects to the ajax post method.

JS:

var array1 = [];
var array2 = [];

array1.push({ modelNumber:partNo , qty: 1 });
array2.push({ modelNumber:partNo , qty: 2 });

var jsonData = { "key1" : array1, "key2" : array2};

$.ajax({
url : formURL,
type: "POST",
data: JSON.stringify(jsonData),
dataType : "JSON",
processData:false,
async: false,
cache: false,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success:function(data, textStatus, jqXHR) {
//some code
}
});


The JSON that is getting posted is (took from console and formatted),

{
"key1":[
{"modelNumber":"95000-8740","qty":"2"},
{"modelNumber":"9500098740","qty":"5"}
],
"key2":[
{"modelNumber":"94100-0561","qty":"2"},
{"modelNumber":"2941780060","qty":"3"}
]
}


Class:

public class ModelQtyArray{

private ModelQtyMap[] key1;
private ModelQtyMap[] key2;

//getter and setters
}

public class ModelQtyMap{

private String modelNumber;
private String qty;

//getters and setters
}


Spring controller:

@RequestMapping(value="/processSaveData", method = RequestMethod.POST,consumes={ "application/json" })
public @ResponseBody void processSave(@RequestBody ModelQtyArray jsonData){
System.out.println("JSON value " + jsonData);
}


jsonData
is printing the null values. I'm not able to get the values in the json object.

In Console I get
JSON value [key1=null, key2=null]


What's wrong with the code? Is my model object in correct format with the JSON object posted?

Answer

See the following code, I have modified certain portions to show that data is successfully posted to the server.

Java

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

    @SpringBootApplication
    public class Application {

        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }

    @RestController
    class RestTest {
        @RequestMapping(value = "/processSaveData", method = RequestMethod.POST, consumes = { "application/json" })
        public @ResponseBody String processSave(@RequestBody ModelQtyArray jsonData) {
            System.out.println("JSON value " + jsonData.getKey1().length + " : " + jsonData.getKey2().length);
            ObjectMapper mapper = new ObjectMapper();
            String json = null;
            try {
                json = mapper.writeValueAsString(jsonData);

                System.out.println("array key1 " + mapper.writeValueAsString(jsonData.getKey1()));
                System.out.println("array key2 " + mapper.writeValueAsString(jsonData.getKey2()));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            System.out.println("Object Mapper json : " + json);


            return json;
        }
    }

    @Controller
    class TestController {
        @RequestMapping("/")
        public String index() {
            return "index";
        }
    }

    class ModelQtyArray {
        private ModelQtyMap[] key1;
        private ModelQtyMap[] key2;

        public ModelQtyMap[] getKey1() {
            return key1;
        }
        public void setKey1(ModelQtyMap[] key1) {
            this.key1 = key1;
        }
        public ModelQtyMap[] getKey2() {
            return key2;
        }
        public void setKey2(ModelQtyMap[] key2) {
            this.key2 = key2;
        }
    }

    class ModelQtyMap {
        private String modelNumber;
        private String qty;

        public String getModelNumber() {
            return modelNumber;
        }
        public void setModelNumber(String modelNumber) {
            this.modelNumber = modelNumber;
        }
        public String getQty() {
            return qty;
        }
        public void setQty(String qty) {
            this.qty = qty;
        }
    }

Following is the HTML page mapped to "/" put it inside src/resources/template

index.html

<html>
<head>
    <script   src="https://code.jquery.com/jquery-3.1.0.min.js"   integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="   crossorigin="anonymous"></script>
    <script>
        console.log(jQuery);

        var array1 = [];
        var array2 = [];

        array1.push({ modelNumber:1 , qty: 1 });
        array2.push({ modelNumber:2 , qty: 2 });

        var jsonString = { "key1" : array1, "key2" : array2};

        $(function () {
            $.ajax({
                url : "http://localhost:8080/processSaveData",
                type: "POST",
                data:  JSON.stringify(jsonString),
                dataType : "JSON",
                processData:false,
                async: false,
                cache: false,
                headers: { 
                    'Accept': 'application/json',
                    'Content-Type': 'application/json' 
                },
                success:function(data, textStatus, jqXHR) {
                    var preData = "<pre>" + JSON.stringify(data, null, 1) + "</pre>";
                    $("body").append(preData);
                }
            });
        })
    </script>
</head>
<body>
</body>
</html>

This would be rendered using Thymeleaf

To include Thymeleaf add following dependency.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>