如何使用Map构造复杂的json结构在java中
我正在与此 问题
总结是,我正在做一个简单的http POST,使用json数据作为http正文。我得到的不是 200 响应,而是 403,在我深入研究为什么我认为我会在我引用的问题中采纳用户的建议并使用此 Map 结构手动构造一个 json 字符串之前。唯一的问题是我不确定如何对如下所示的复杂结构执行此操作(例如,地图是否应该包含地图的地图)
{"context":{"locationdata":{"lat":41.5816456,"lng":-93.62431329999998}},"results":{"less":150,"on":true,"off":true,"status":true,"working":true,"item":[1111]}}
提前谢谢
I'm fighting a similar 403 error found in this question
The summary is that I'm doing what should be a simple http POST w/ json data as the http body. Instead of a 200 response I'm getting 403 and before I dive deep into why I thought I would take the advice of the user in the question I referenced and construct a json string by hand using this Map structure. The only issue is I'm not sure how to do this for a complex structure like the below (should the map contain maps of maps for example)
{"context":{"locationdata":{"lat":41.5816456,"lng":-93.62431329999998}},"results":{"less":150,"on":true,"off":true,"status":true,"working":true,"item":[1111]}}
Thank you in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我参与的一个项目中,我们创建了自己的 json 生成工具,并做了一些非常相似的事情。映射表示对象文字,列表表示数组。所以我们有地图,有列表,有地图。我们的实用程序将检查每个属性的类型,如果它是列表,则调用一个方法,如果它是映射,则递归地调用另一个方法。我们的 util 具有像“
如果您想推出自己的,您尝试做的事情是可能的”这样的方法,即使对于深度嵌套的结构也是如此。我们的 util 大约有 100 行代码。然而,现在有很好的第三方库可以做到这一点。
请注意,在您的问题标题中您提到了
Map
。您必须将其更改为Map
或Map
之类的内容,因为地图中的值绝对不能仅限于字符串。On a project I worked on once we created our own json generation tool, and did something quite similar. Maps represented object-literals, and Lists represented arrays. So we had maps that had lists that had maps. Our utility would check the type of each property, and if it were a list call one method, and if it were a map call another method, recursively. Our util had methods like
If you want to roll your own, what you are trying to do is possible, even for deeply nested structures. Our util was around 100 lines of code. However, now there exist good third party libraries to do this.
Note that in your question title you mention
Map<String, String>
. You would have to change it to something likeMap<String, ?>
orMap<String, Collection>
since the values in the map definitely cant be confined to Strings.