1

I tried to process the request with the example below:

"type" : "NEWS",
"content" : {
    "title" : "Test Message",
    "message" : "This is a message",
    "buttonCaption" : "Click me"
}

Or maybe:

"type" : "NEWS",
"content" : {
    "title" : "Test Message",
    "message" : "This is a message",
    "buttonCaption" : "Click me",
    "anotherField" : "values"
}

Sometime maybe:

"type" : "NEWS",
"content" : {
    "name" : "Test Message",
    "anotherProperties" : "This is a message",
    "ohMyGodAnotherFields" : "Click me"
}

So I cannot create a particular Object. How can I handle it in Spring controller?

Loc Le
  • 537
  • 1
  • 8
  • 21
  • it looks to be a duplicate: of this: https://stackoverflow.com/questions/7304002/how-to-parse-a-dynamic-json-key-in-a-nested-json-result – DDS May 25 '18 at 09:11

2 Answers2

0

You can use JsonNode in your resource class like:

public class Foo {
    private String type;
    private JsonNode content;
    // ...
}

And accept it as @RequestBody in your controller:

@PostMapping
public ResponseEntity<Foo> foo(@RequestBody Foo foo){
   // do something with your foo...
}

You can read more aboot JsonNode here.

mkuligowski
  • 1,544
  • 1
  • 17
  • 27
0

You have to get the keys, using java.util.Iterator.

JSONObject jsonObj = new JSONObject(JSONString);
Iterator keys = jsonObj.keys();
while (keys.hasNext()) {
     String keyStr = keys.next().toString();
     String value = jsonObj.getStrin(keyStr);
}

or You can try this:

JSONObject jsonObj = new JSONObject(JSONString);
if (jsonObj.has("key")) {
    String value = jsonObj.getString("key");
}
HanAn
  • 1
  • 2