简体   繁体   中英

How do I receive a JSONObject from post on spring boot rest controller (from org.json)

I want my RESTcontroller to get a JSONObject from a post request but when I send this through Postman:

{
    "collection":"StudentDB",
    "index":{
        "joinDate":"2022-12-12"
    }
}

It seems to be working, but the problem is that embedded JSONObjects seem to get cast into a LinkedHashmap and not be JSONObjects, so when I run this code:

@PostMapping
@RequestMapping(value="/query",consumes="application/json")
public ResponseEntity query( @RequestBody JSONObject query) {
    System.out.println(query.get("index").getClass());
}

Output is:

class java.util.LinkedHashMap

What could be causing this? Is there another way I could do this?

It looks like the reason why you get java.util.LinkedHashMap value for index key is because under the hood JSONObject uses a Map to store it's key-value pairs.

So each key-value pair(for example, "collection": "StudentDB") is actually stored in this map that's wrapped in a JSONObject.

And when you wrote "index": { key-value pairs here }, you essentially told JSONObject that you want to create another Map(for key-value pairs that will be inside of { }) that will be serving as a value for index key.

As for why LinkedHashMap is used here, the reason for that is because JSONObject needs to preserve the ordering of its elements, so LinkedHashMap does just that.

The solution to your problem depends on what you're exactly trying to achieve here. The logic of the program seems to be okay, so hopefully you'll figure out what to do about it based on what I've written here.

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