开发者

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

开发者 https://www.devze.com 2023-03-06 15:11 出处:网络
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

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


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

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. 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 like Map<String, ?> or Map<String, Collection> since the values in the map definitely cant be confined to Strings.

0

精彩评论

暂无评论...
验证码 换一张
取 消