简体   繁体   中英

How to accept dynamic json response and add one key-value to that object and return that same JSONObject from the spring boot controller

My controller is receiving post request as dto object and my dto has one Object array which is used to get the array of json objects, I have to add one key-value to each json object in that array and return it back.

dto class:

public class FileProcessDTO {

    private String module;
    private Object[] data;

    public String getModule() {
        return module;
    }
    public void setModule(String module) {
        this.module = module;
    }
    public Object[] getData() {
        return data;
    }
    public void setData(Object[] data) {
        this.data = data;
    }
}

below is controller method

@PostMapping("/processData")
    public FileProcessDTO processFileData(@Valid @RequestBody FileProcessDTO fileProcess) throws JSONException {

        String module = fileProcess.getModule();
        Object[] objects= fileProcess.getData();

        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray(fileProcess.getData());

        FileProcessDTO fileProcessDTO = new FileProcessDTO();
        fileProcessDTO.setModule(module);


        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                jsonObject = jsonArray.getJSONObject(i);
                jsonObject.put("status", true);
            } catch (Exception e) {
                jsonObject.put("status", false);
                jsonObject.put("error", e.getMessage());
            }


            objects[i]=jsonObject;

        }
        fileProcessDTO.setData(objects);

        return fileProcessDTO;
    }

and below is the data passed in post request from client

{
"module" : "assignment",
"data":[
    {
        "name": "chandan",
        "age":"27"
    },
    {
        "name": "Yo",
        "age":"26"
    },
    {
        "name": "Jo",
        "age":"25"
    }
]
}

In above objects of "data" array keys and values will be different in different request(may be in next request "name" and "age" will changed).

Below I am getting error.

org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.springframework.boot.configurationprocessor.json.JSONObject]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.boot.configurationprocessor.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.crisil.apg.service.dto.FileProcessDTO["data"]->org.springframework.boot.configurationprocessor.json.JSONObject[0])
2019-04-17 12:04:14.002  WARN 10808 --- [nfoReplicator-0] c.n.discovery.InstanceInfoReplicator     : There was a problem with the instance info replicator

I also tried to change line in controller method as below but, its not as json response.

objects[i]=jsonObject.toString();

//below is response
{
    "module": "assignment",
    "data": [
        "{\"name\":\"chandan\",\"age\":\"27\",\"status\":true}",
        "{\"name\":\"Yo\",\"age\":\"26\",\"status\":true}",
        "{\"name\":\"Jo\",\"age\":\"25\",\"status\":true}"
    ]
}

Kindly suggest the possible code to make it work.Thanks.

You can use String as request body then convert the string to JSONObject and do the processing.

@PostMapping(value="/get",consumes={"application/json"})
    public ResponseEntity<?> test(@RequestBody String req){

        //String to JSON Object
        JSONObject obj= new JSONObject(req);
        JSONArray arr=(JSONArray)obj.get("arr");

        //Adding ID to JSON ARRAY
        for(int i=0;i<arr.length();i++){
            JSONObject ob=(JSONObject)arr.get(i);
            ob.append("id", "id-"+i+1);
            arr.put(i, ob);
        }
        return new ResponseEntity<>(arr.toString(),HttpStatus.OK);
    }

I tried recreating above issue with the input you mentioned above, Instead of any error, I got below response on postman:

{
"module": "assignment",
"data": [
    {
        "empty": false
    },
    {
        "empty": false
    },
    {
        "empty": false
    }
]

}

Logs on my console :

2019-04-17 13:24:30.128 DEBUG IND-PBHUITE
            --- [nio-8081-exec-3] o.s.w.s.DispatcherServlet                : POST "/processData/", parameters={}
2019-04-17 13:24:30.129 DEBUG IND-PBHUITE
            --- [nio-8081-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public com.noobcompany.metrostation.model.FileProcessDTO com.noobcompany.metrostation.controller.MainController.processFileData(com.noobcompany.metrostation.model.FileProcessDTO)
2019-04-17 13:24:30.130 DEBUG IND-PBHUITE
            --- [nio-8081-exec-3] m.m.a.RequestResponseBodyMethodProcessor : Read "application/json;charset=UTF-8" to [com.noobcompany.metrostation.model.FileProcessDTO@36c525]
2019-04-17 13:24:30.130 DEBUG IND-PBHUITE
            --- [nio-8081-exec-3] m.m.a.RequestResponseBodyMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
2019-04-17 13:24:30.131 DEBUG IND-PBHUITE
            --- [nio-8081-exec-3] m.m.a.RequestResponseBodyMethodProcessor : Writing [com.noobcompany.metrostation.model.FileProcessDTO@f12f53]
2019-04-17 13:24:30.132 DEBUG IND-PBHUITE
            --- [nio-8081-exec-3] o.s.w.s.DispatcherServlet                : Completed 200 OK

I am using SpringBoot 2.1.4.RELEASE with RestController and using below dependency for JsonObject

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM