我在下面创建了JSON Object
,但我不知道如何用JSONStringer填充参数字段?参数字段是JSONArray
还是Array String
?
{"name":"Katy", "parameters":["JAK","1999"], "Age":25}
感谢您的帮助。
答案 0 :(得分:0)
尝试以下
String mParameters[] = { "JAK", "1999" };
JSONObject mJson = new JSONObject();
try {
mJson.put("name", "Katy");
JSONArray mJSONArray = new JSONArray(Arrays.asList(mParameters));
mJson.putOpt("parameters", mJSONArray);
mJson.put("Age", 25);
System.out.println("JSon::"+ mJson.toString());
} catch (JSONException e) {
e.printStackTrace();
}
答案 1 :(得分:0)
The documentation for JSON将告诉您,区分您的JSON字符串是一个数组的一种简单方法是它是以[
开头,所以"参数"在您的示例中是JSONArray
。
在不知道如何获取要放入对象的数据的情况下,这里有一个如何填充它的示例(假设您有一个JAKS
数组要插入)。
JSONObject yourObject = new JSONObject();
String[] JAKS = {"1999", "2000", "2001"};
JSONArray paramaters = new JSONArray();
try {
yourObject.put("name", "Katy");
for (String JAK : JAKS) {
JSONObject yourParamater = new JSONObject();
yourParamater.put("JAK", JAK);
paramaters.put(yourParamater);
}
yourObject.put("parameters", paramaters);
yourObject.put("Age", 25);
} catch (JSONException e) {
e.printStackTrace();
}
答案 2 :(得分:0)
试试这个:
import org.json.JSONObject;
//other imports
//...
try {
//Create the JSON Object
JSONObject myObject = new JSONObject();
String parameters[] = new String[]{"JAK","1999"};
//use the method put to "fill" the values
myObject.put("name", "Katy");
myObject.put("parameter",(Object)parameters);
myObject.put("age", 25);
} catch (JSONException e) {
e.printStackTrace();
}
答案 3 :(得分:0)
请尝试这种方式,希望这有助于您解决问题。
try{
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","Katy");
jsonObject.put("parameters",new String[]{"JAK","1999"});
jsonObject.put("Age","25");
}catch (Throwable e){
e.printStackTrace();
}