Reputation: 121
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?
Upvotes: 0
Views: 570
Reputation: 31
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.
Upvotes: 1