0

Hi i want to create json string like

{"id":"12345","option-ids":["100"]}

i've tried like below

JSONObject object = new JSONObject();

            try {

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

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

but i struck on create json array withou object name.

2 Answers 2

1
// 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();
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Using GSON library is easiest way sample here: mkyong.com/java/…
sure, I use GSON in my apps, but for that regular Json library is enough
0

To insert String in JSONArray,use put() method of JSONArray. try below code.

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();
            }

You should use JSONArray (from org.json) instead of JsonArray(from com.google.gson)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.