[英]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:我希望我的 RESTcontroller 从发布请求中获取 JSONObject,但是当我通过 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:它似乎在工作,但问题是嵌入式 JSONObjects 似乎被转换为 LinkedHashmap 而不是 JSONObjects,所以当我运行这段代码时:
@PostMapping
@RequestMapping(value="/query",consumes="application/json")
public ResponseEntity query( @RequestBody JSONObject query) {
System.out.println(query.get("index").getClass());
}
Output is: Output 是:
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.看起来你得到 java.util.LinkedHashMap 索引键值的原因是因为在引擎盖下 JSONObject 使用 Map 来存储它的键值对。
So each key-value pair(for example, "collection": "StudentDB") is actually stored in this map that's wrapped in a JSONObject.所以每个键值对(例如,“collection”:“StudentDB”)实际上存储在这个 map 中,它被包装在一个 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.当你写 "index": { key-value pairs here } 时,你基本上告诉 JSONObject 你想要创建另一个 Map(对于将在 { } 内的键值对),它将作为 index 的值钥匙。
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.至于这里为什么使用LinkedHashMap,是因为JSONObject需要保留其元素的顺序,所以LinkedHashMap就是这样做的。
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.
该程序的逻辑似乎没问题,所以希望您能根据我在这里写的内容弄清楚该怎么做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.