java - json官方java api : JSONArray of JSONObjects

标签 java json

萨拉姆,

使用 json.org API,我们可以轻松地将 map 转换为 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 不提供这个,是吗?

至少,将 JSONObject 添加到 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 ?它专注于Java对象到JSon和Json到Java对象。

关于java - json官方java api : JSONArray of JSONObjects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3652326/

相关文章:

java - 在 GPS 和网络之间切换?

java - 如何在 VisualVM 中显示调用树?

java - PHP 相当于 JAVA HexUtils.bytesToHex()

java - Spring Framework XML 配置元数据和命名空间

java - 休息问题 使用rest easy的服务

json - 使用 jq 在 json 中进行类似正则表达式的搜索

javascript - Cytoscape Cola.js 布局边长 = 文本语料库可视化

javascript - mustache 模板不在表 tbody 内呈现

java - libGDX actor 在运动时不会表现得正确

php zend框架json解码失败