我正在努力用 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"]}]};
最佳答案
你的 s
是 String
在 put
时不不加引号进入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/