如何在java </string,>中使用Map <string,string =“”>构造复杂的json结构

时间:2011-05-16 02:03:39

标签: java json http

我正在解决此question

中发现的类似403错误

总结是我正在做一个简单的http POST w / json数据作为http正文。在我深入了解为什么我认为我会在我引用的问题中采用用户的建议并使用此Map结构手动构造json字符串之前,而不是200响应我得到403。唯一的问题是我不知道如何为下面的复杂结构(如果地图包含地图的地图)这样做

{"context":{"locationdata":{"lat":41.5816456,"lng":-93.62431329999998}},"results":{"less":150,"on":true,"off":true,"status":true,"working":true,"item":[1111]}}

提前谢谢

1 个答案:

答案 0 :(得分:1)

在我创建了自己的json生成工具后,我开始研究的项目,做了类似的事情。 Maps表示对象文字,Lists表示数组。所以我们有包含地图的列表的地图。我们的实用程序将检查每个属性的类型,如果它是一个列表调用一个方法,如果它是一个地图调用另一个方法,递归。我们的util有像

这样的方法
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
}

如果你想自己动手,那么即使对于深层嵌套的结构,你也可以尝试做。我们的util大约有100行代码。但是,现在有很好的第三方库可以做到这一点。

请注意,在您的问题标题中,您提到了Map<String, String>。您必须将其更改为Map<String, ?>Map<String, Collection>,因为地图中的值绝对不能局限于字符串。