java - 如何使用 net.sf.json 在 Java 中生成 JSON 字符串?

标签 java json

我正在努力用 Java 生成 JSON 字符串。

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

JSONArray ja = new JSONArray();
JSONObject js = new JSONObject();
JSONObject j = new JSONObject();

String s = "[{\"shakil\",\"29\",\"7676\"}]";

js.put("id", "1");
js.put("data", s);
ja.add(js);

j.put("rows", ja);

System.out.println(j.toString());

实际输出:

{"rows":[{"id":"2","data":"[{\"shakil\",\"29\",\"7676\"}]"}]}

预期输出:

{"rows":[{"id":"2","data":["shakil", "29","7676"]}]};

最佳答案

你的 sStringput不加引号进入JSONObject .你必须再建一个 JSONArray对于 data 的值:

// using http://jettison.codehaus.org/
JSONObject outerObject = new JSONObject();
JSONArray outerArray = new JSONArray();
JSONObject innerObject = new JSONObject();
JSONArray innerArray = new JSONArray();

innerArray.put("shakil");
innerArray.put("29");
innerArray.put("7676");

innerObject.put("id", "2");
innerObject.put("data", innerArray);

outerArray.put(innerObject);

outerObject.put("rows", outerArray);

System.out.println(outerObject.toString());

结果:

{
    "rows": [
        {
            "id": "2",
            "data": [
                "shakil",
                "29",
                "7676"
            ]
        }
    ]    
}

关于java - 如何使用 net.sf.json 在 Java 中生成 JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13340138/

相关文章:

python - 以点表示法返回 python 嵌套 dict/json 文档中所有变量名称的列表

javascript - 使用 GWT 时找不到 Firebase Service worker(404 错误)

java - 如何在本地使用java使用spark连接到Google大查询?

javascript - 未捕获的类型错误 :undefiened is not a function for JSON response

javascript - 从 JSON 响应对象在 Angular 中创建一个类

java - JSON:将对象转换为数组

java - 无法将 JSON 映射到 Java bean

java - 再次玩猜数字游戏

java - 谷歌日历

javascript - 使用变量构建 JS 对象