Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JSON format data in android?

Tags:

json

android

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

like image 528
Harish Avatar asked May 23 '12 10:05

Harish


People also ask

What is JSON in android with example?

JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it. Android provides four different classes to manipulate JSON data.

How JSON is used in android?

Android supports all the JSON classes such as JSONStringer, JSONObject, JSONArray, and all other forms to parse the JSON data and fetch the required information by the program. JSON's main advantage is that it is a language-independent, and the JSON object will contain data like a key/value pair.

What is JSON format with example?

JSON stands for Javascript Object Notation. JSON is a text-based data format that is used to store and transfer data. For example, // JSON syntax { "name": "John", "age": 22, "gender": "male", } In JSON, the data are in key/value pairs separated by a comma , . JSON was derived from JavaScript.


2 Answers

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"
             ]
           }
         }
like image 54
Lalit Poptani Avatar answered Sep 29 '22 12:09

Lalit Poptani


You can use JSONObject and construct your data with it.

Here is the Documentation link

jsonObject.toString() // Produces json formatted object
like image 41
ChristopheCVB Avatar answered Sep 29 '22 12:09

ChristopheCVB