创建Jsonstring-Android

创建Jsonstring-Android,android,android-json,Android,Android Json,嗨,我想创建json字符串,就像 {"id":"12345","option-ids":["100"]} 我试过下面的方法 JSONObject object = new JSONObject(); try { object.put("id","12314"); JsonArray jsonArray = new JsonArray(); jsonArray......

嗨,我想创建json字符串,就像

{"id":"12345","option-ids":["100"]}
我试过下面的方法

JSONObject object = new JSONObject();

            try {

            object.put("id","12314");
            JsonArray jsonArray = new JsonArray();
            jsonArray......

            object.put("option-ids",""+jsonArray);
            } catch (JSONException e) {
                e.printStackTrace();
            }

但是我突然想到用你的对象名创建json数组。

要在
JSONArray
中插入字符串,请使用
JSONArray
put()
方法。 试试下面的代码

JSONObject object = new JSONObject();

            try {

            object.put("id","12345");
            JSONArray jsonArray = new JSONArray();
            jsonArray.put("100"); //add here
            object.put("option-ids",jsonArray.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }

您应该使用
JSONArray
(来自org.json)而不是
JSONArray
(来自com.google.gson)

使用gson库是最简单的方法示例:当然,我在我的应用程序中使用gson,但对于常规的json库就足够了
// First - create the json Object
    JSONObject object = new JSONObject();
    try {
        // Add the id to the json
        object.put("id", "12314");
        // Create a json array
        JSONArray jsonArray = new JSONArray();
        // Put the values you want
        jsonArray.put("1");
        jsonArray.put("2");
        object.put("option-ids",jsonArray.toString());
    } catch (JSONException e) {
        // Handle impossible error
        e.printStackTrace();
    }