In last tutorial JSON Parser we learned how to parse JSON data from local file and from server. Sometimes we have to send data to server in JSON format like to store address in server database, etc. so for that we have to encode our data into JSON for server. For this Android provide us several methods to create JSON.
Before proceeding we need to know some methods that we are going to use :
1 2 |
//Creating Json Object JSONObject dataObject = new JSONObject(); |
1 2 |
//creating Json Array JSONArray mainArray = new JSONArray(); |
1 2 |
JsonObject dataObject = new JsonObject(); dataObject.put("key_value", value);//put data in json object |
1 2 |
JsonArray array = new JsonArray(); array.put(dataObject);//Putting Json Object into Json Array |
1 2 |
JsonObject mainObject = new JsonObject(); mainObject.put("key-value", your_jsonarray);//inserting json array |
The above methods are going to be used in this tutorial. So lets start with tutorial.
In this tutorial, we are going to learn how to create JSON data both in JSON Array ([) and JSON Object ({).
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. Firstly, open res ⇒ values ⇒ strings.xml and add below string values. This are some strings that i am going to use.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">JsonMaker Demo</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="submit">Submit</string> <string name="full_name">Full Name</string> <string name="location">Location</string> <string name="number">Contact Number</string> <string name="age">Age</string> </resources> |
3. Now, create a simple layout xml file that contains some edittext and one textview for displaying Json encoded data. You can take any view according to your need.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff" android:orientation="vertical" android:padding="5dp" > <EditText android:id="@+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:hint="@string/full_name" android:inputType="text" android:padding="10dp" android:textColor="#000000" android:textColorHint="#d3d3d3" android:textSize="15sp" /> <EditText android:id="@+id/location" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:hint="@string/location" android:inputType="text" android:padding="10dp" android:textColor="#000000" android:textColorHint="#d3d3d3" android:textSize="15sp" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <EditText android:id="@+id/contact_number" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:layout_weight="1" android:hint="@string/number" android:inputType="number" android:padding="10dp" android:textColor="#000000" android:textColorHint="#d3d3d3" android:textSize="15sp" /> <EditText android:id="@+id/age" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:layout_weight="1" android:hint="@string/age" android:inputType="number" android:padding="10dp" android:textColor="#000000" android:textColorHint="#d3d3d3" android:textSize="15sp" /> </LinearLayout> <Button android:id="@+id/submit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="5dp" android:gravity="center" android:padding="7dp" android:text="@string/submit" /> <!-- TextView for displaying converted json data --> <TextView android:id="@+id/show_jsondata" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:padding="10dp" android:textColor="#ff6600" android:textSize="18sp" /> </LinearLayout> |
4. Finally come to your main java class naming MainActivity.java and add the following code. In this class i fetched all the values from edittexts and encode it into JSON data by using Json methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
package com.jsonmaker_demo; import org.json.JSONArray; import org.json.JSONObject; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private static EditText name, location, age, number; private static TextView showJsonData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } // Initialize all the views private void init() { name = (EditText) findViewById(R.id.name); location = (EditText) findViewById(R.id.location); age = (EditText) findViewById(R.id.age); number = (EditText) findViewById(R.id.contact_number); showJsonData = (TextView) findViewById(R.id.show_jsondata); // Click listener for submit button findViewById(R.id.submit).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // Call the json data convertor method ConvertToJsonData(); } }); } // Method to convert simple data into jsondata private void ConvertToJsonData() { // get texts from all edittexts String getName = name.getText().toString(); String getLocation = location.getText().toString(); String getNumber = number.getText().toString(); String getAge = age.getText().toString(); // Check if all fields are filled or not if (getName.length() != 0 && !getName.equals("") && getLocation.length() != 0 && !getLocation.equals("") && getNumber.length() != 0 && !getNumber.equals("") && getAge.length() != 0 && !getAge.equals("")) { try { JSONObject dataObject = new JSONObject();// JsonObject for // storing edittext // fields dataObject.put("name", getName);// now put the edittext values // w.r.t. keyvalue like "name" dataObject.put("location", getLocation); dataObject.put("number", getNumber); dataObject.put("age", getAge); JSONArray mainArray = new JSONArray();// JsonArray to put the // dataObject into // jsonArray, since // there can be more // data if data is saved // in database so the // jsonObject data will // be put into jsonArray mainArray.put(dataObject); // Finally put the jsonArray into another jsonObject with "data" // keyvlaue or any other keyvalue JSONObject mainObject = new JSONObject(); // This object is // optional you can // convert json data // according to your // need mainObject.put("data", mainArray); // Now, set the converted json data to textview to see the // actual format showJsonData.setText("Converted JSON data is nn" + mainObject.toString()); } catch (Exception e) { e.printStackTrace(); // If any exception occurs then display error showJsonData.setText("Error in converting data."); } } // If all fileds or one of the filed is empty show toast else { Toast.makeText(MainActivity.this, "All fields are required.", Toast.LENGTH_SHORT).show(); } } } |
5. Now, you are all done, run your app.
Thanks.
Subscribe to us and get the latest news.
2 Comments
Amitabh
Tuesday, May 3rd, 2022How to save the JSONObject (mainObject) to a JSON File (example data.json) ?
Dr. Droid
Tuesday, May 3rd, 2022Hi Amitabh,
You can check this link: https://www.androhub.com/android-read-write-file-operations/.
Instead of .txt use .json for creating file.
Thanks