萨拉姆
使用json.org API,我们可以轻松地将地图转换为JSON对象:
Map<String, String> carta = new Map<String, String>();
carta.put( "id", "123");
carta.put( "Planet", "Earth");
carta.put( "Status", "getting dirty");
JSONObject json = new JSONObject();
for(Iterator<String> it=input.keySet().iterator(); it.hasNext();){
String key = it.next();
json.put(key, input.get(key));
}
System.out.println(json.toString());
// output: {id:"123", Planet:"Earth", Status: "getting dirty"}
现在我们要有一个这些对象的数组
API不提供此功能吗?
至少,将JSONObjects添加到JSONArray可以删除括号:
JSONArray joArr = new JSONArray();
joArr.put( cartaEarth );
joArr.put( cartaMars );
System.out.println( joArr.toString() );
//output: [{ id:123, Planet:Earth, Status: getting dirty }, {id: 456, Planet:Mars, Status: maybe aliens there }]
没有括号...在API中,他们提到:
put(java.util.Map value)
Put a value in the JSONArray, where the value will be a JSONObject which is produced from a Map.
与其先做,不如先讨论,先谢谢!
最佳答案
您尝试过GSon吗?它专门用于JSon和Json到Java Object的Java对象。