Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring Boot RequestBody with JSONObject

I’m tring set my RestController to receive a json with another json inside of this (I don’t now the structure of that second json)…
something like that:

{
    "field1":"value1",
    "jsonField":{
        "anotherField1":1,
        "anotherField2":0.2
    }
}

And my request class is like that:

public class Request {
    private String field1;
    private org.json.JSONObject jsonField;
}

But when i call my controller, field1 is setted, but jsonField doesn’t. It’s setted only with {}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT: This is the controller method:

@PostMapping
public ResponseEntity postMethod(@RequestBody Request request) {}

>Solution :

You need to define your own class for the jsonField object if you want it to be mapped automatically.

public class Request {
    private String field1;
    private JsonField jsonField;
}

public class JsonField {
    private Integer anotherField1;
    private Integer anotherField2;
}

If you don’t know its structure beforehand, the approach will be different. You can use either a Map:

public class Request {
    private String field1;
    private Map<String, Object> jsonField;
}

or Jackson’s JsonNode type

public class Request {
    private String field1;
    private JsonNode jsonField;
}

You can read about it more here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading