我正在尝试在android上创建这个JSON对象。我纠结于如何在对象中添加字符串数组。
A = {
"class" : "4" ,
"name" : ["john", "mat", "jason", "matthew"]
}
这是我写的代码:
import org.json.JSONObject;
JSONObject school = new JSONObject();
school.put("class","4");
school.put("name", ["john", "mat", "jason", "matthew"] );
但是最后一行给出了一个错误。还有别的办法吗?
发布于 2013-10-16 20:20:11
汤姆建议的一些不恰当的方法。优化后的代码将是:
ArrayList<String> list = new ArrayList<String>();
list.add("john");
list.add("mat");
list.add("jason");
list.add("matthew");
JSONObject school = new JSONObject();
school.put("class","4");
school.put("name", new JSONArray(list));
发布于 2013-03-31 21:10:45
你得到一个错误,因为你的最后一行是无效的Java。
school.put("name", new JSONArray("[\"john\", \"mat\", \"jason\", \"matthew\"]"));
发布于 2013-03-31 21:00:55
正因为如此,你得到了错误。
school.put("name", ["john", "mat", "jason", "matthew"] );
^ ^
像这样做。
school.put("name", new JSONArray("[\"john\", \"mat\", \"jason\", \"matthew\"]"));
https://stackoverflow.com/questions/15729598
复制相似问题