Home > Software engineering >  Spring Boot RequestBody with JSONObject
Spring Boot RequestBody with JSONObject

Time:11-26

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 {}

EDIT: This is the controller method:

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

CodePudding user response:

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.

  • Related