Android JSON Maker - Androhub

JSON Maker

Android JSON Maker

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 :

  • Creating JSON Object

  • Creating JSON Array

  • Putting/Inserting values inside Json Object  : You can put any type of data in  Json like string, int, boolean, float, etc with keyvalue.

  • Adding Json Object into Json Array  : We can add any data to Json Array also.

  • Similarly adding Json Array into Json Object

The above methods are going to be used in this tutorial. So lets start with tutorial.

Example

In this tutorial, we are going to learn how to create JSON data both  in JSON Array ([) and JSON Object ({).

VIDEO DEMO

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.

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.

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.

5. Now, you are all done, run your app.

Thanks. :)

 

2 Comments

Amitabh
Tuesday, May 3rd, 2022

How to save the JSONObject (mainObject) to a JSON File (example data.json) ?

Dr. Droid
Tuesday, May 3rd, 2022

Hi Amitabh,

You can check this link: https://www.androhub.com/android-read-write-file-operations/.
Instead of .txt use .json for creating file.

Thanks

Post comment

Your email address will not be published. Required fields are marked *