简体   繁体   English

如何使用Map构造复杂的json结构 <String, String> 在java中

[英]How to construct a complex json structure using Map<String, String> in java

I'm fighting a similar 403 error found in this question 我正在解决这个问题中发现的类似403错误

The summary is that I'm doing what should be a simple http POST w/ json data as the http body. 摘要是,我正在做一个简单的带有JSON数据的http POST,并将其作为http正文。 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. 而不是200的响应,我得到403,然后再深入探讨为什么我认为我会在所引用的问题中听取用户的建议,并使用此Map结构手动构造json字符串。 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 先感谢您

On a project I worked on once we created our own json generation tool, and did something quite similar. 创建了自己的json生成工具后,在一个我从事的项目中,所做的事情非常相似。 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 我们的工具有类似

public String writeJson(Map map, String json) {
   /*
      Code that looped thru the entries of the map and determined whether to 
      1.  add a property to the String for a simple type
      2.  recurse into this method if the entry contained a Map
      3.  call writeJson(list) if the entry contained  a List
   */
}

public String writeJson(List list, String json) {
   // same comment as above
}

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. 我们的工具大约有100行代码。 However, now there exist good third party libraries to do this. 但是,现在有好的第三方库可以做到这一点。

Note that in your question title you mention Map<String, String> . 请注意,在您的问题标题中提到了Map<String, String> You would have to change it to something like Map<String, ?> or Map<String, Collection> since the values in the map definitely cant be confined to Strings. 您必须将其更改为Map<String, ?>Map<String, Collection>因为地图中的值绝对不能限制为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM