How to create JSON format data in android?

android, json

Solution

Its not that though at all, output you want is JSONArray inside JSONObject and JSONObject inside another JSONObject. So, you can create them seperately and then can put in together. as below.

try {
            JSONObject parent = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            jsonArray.put("lv1");
            jsonArray.put("lv2");

            jsonObject.put("mk1", "mv1");
            jsonObject.put("mk2", jsonArray);
            parent.put("k2", jsonObject);
            Log.d("output", parent.toString(2));
        } catch (JSONException e) {
            e.printStackTrace();
        }

Output-

       {
           "k2": {
             "mk1": "mv1",
             "mk2": [
               "lv1",
               "lv2"
             ]
           }
         }

Problem

I need to pass some parameters to server that i need to pass as below format ``` { "k2": { "mk1": "mv1", "mk2": [ "lv1", "lv2" ] } } ``` So how can generate this format in android. I tried this using the As shown in example 5.3 but it is showing a error at `obj.writeJSONString(out);` this line. Can anyone please help in solving this. Thanks In Advance

Original source