0

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) {}
asked Nov 25, 2021 at 22:11

1 Answer 1

2

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.

answered Nov 25, 2021 at 22:27
Sign up to request clarification or add additional context in comments.

4 Comments

but I don't now the strcture of the jsonField...
You need to state it in the question then, as it changes the approach.
@Teofilo, please see my updated answer.
The Map solution solved this. Thanks

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.