Skip to main content

Dealing with Jsonobject Java Tutorial with Example Explained

Dealing with Jsonobject Java language, if you've some data in JSON format and are trying to parse it in some readable format for the user using Java programming, then you're reading the right blog!

In this tutorial we will be using Android Studio in which using Java programming we will parse the JsonObject that we will receive from the server and text will be displayed in TextView.

Jsonobject Java Tutorial 


Here is the sample JSONObject data:


[
 {
   "name": "Afghanistan",
   "alpha": "AFG"
 },
 {
   "name": "Åland Islands",
   "alpha": "ALA"
 },
 {
   "name": "Albania",
   "alpha": "ALB"
 },
 {
   "name": "Algeria",
   "alpha": "DZA"
 },
 {
   "name": "American Samoa",
   "alpha": "ASM"
 },
 {
   "name": "Russian Federation",
   "alpha": "RUS"
 },
 {
   "name": "Rwanda",
   "alpha": "RWA"
 },
 {
   "name": "Saint Barthélemy",
   "alpha": "BLM"
 },
 {
   "name": "Saint Helena, Ascension and Tristan da Cunha",
   "alpha": "SHN"
 },
 {
   "name": "United Arab Emirates",
   "alpha": "ARE"
 },
 {
   "name": "United Kingdom of Great Britain and Northern Ireland",
   "alpha": "GBR"
 },
 {
   "name": "United States of America",
   "alpha": "USA"
 }


In the sample JSONobject Data shown above in a JSONArray [], we have JSONObjects denoted by {}.  It's a data about Countries and their short name.

To parse JSONObject data using Java programming language you can use following line of code:


JSONArray jsonArray = null;
try {
    jsonArray = new JSONArray(countriesData);
    for(int i = 0; i < jsonArray.length(); i++ ){
    JSONObject jsonObj = jsonArray.getJSONObject(i);    
        String CountryName = jsonObj.getString("name");
        String code = jsonObj.getString("alpha");
    }
        } catch (JSONException e) {
            e.printStackTrace();
        } 


In the code above we have parsed the JSON Data received which consisted of an Array of JSON Objects.

As you can see in the first line we have first set JSONArray as jsonArray and using for loop in Java iterated the whole JSON Data. the jsonObj.getString("name") finds the JSONObject with key name, 'name' and finds the value String and sets it equal to the variable CountryName.

Similarly, the jsonObj.getString("alpha") finds the JSONObject with key name, 'alpha' and finds the value String and sets it equal to the variable code.

However, there may be a case where you have JSONArray inside JSONObjects, lets have a look at following sample data:

{
"kind": "payments",
"items": [
{
"kind": "july#payment",
"id": "unpaid",
"paymentAmount": "12176.88",
"paymentAmountCurrencyCode": "USD"
},
{
"kind": "june#payment",
"id": "2017-08-21",
"paymentDate": "2017-08-21",
"paymentAmount": "12301.34",
"paymentAmountCurrencyCode": "USD"
}
]
}


In the sample data shown above on payments made by a company in the month of June and July, the JSONObject has JSONArrays in it. to parse JSONObject in Java language you can use following line of codes:

JSONObject jsonObject = null;
try {
    jsonObject = new JSONObject(paymentsJSON);
    JSONArray jsonArray = jsonObject.getJSONArray("items");
    for(int i = 0; i < jsonArray.length(); i++ ){
        JSONObject items = jsonArray.getJSONObject(i);
        String payStatus = items.getString("id");
        String payAmt = items.getString("paymentAmount");
        String payCurr = items.getString("paymentAmountCurrencyCode");

As you can see in the first line we have first set the paymentJSON data, JSONObject as jsonObject and then in it searched for key 'item', The value of item is a JSONArray and using for loop in Java iterated the whole item arrays. the items.getString("id") finds the String with key name, 'id' and finds the value String and sets it equal to the variable payStatus.

Similarly, the the items.getString("paymentAmount") finds the String with key name, 'paymentAmount' and finds the value String and sets it equal to the variable payAmt.

Note here that JSON can have any of the following variable types:

  • a string.
  • a number.
  • an object (JSON object)
  • an array.
  • a boolean.
  • null.

Now let's begin an Android tutorial where using Asynctask we will fetch JSONData nd then later parse it in onPostExecute method();

Jsonobject Java Tutorial using Android Studio

The JSONObject data to be fetched in the following tutorial is as follows:

{
"kind": "payments",
"items": [
{
"kind": "july#payment",
"id": "unpaid",
"paymentAmount": "12176.88",
"paymentAmountCurrencyCode": "USD"
},
{
"kind": "june#payment",
"id": "2017-08-21",
"paymentDate": "2017-08-21",
"paymentAmount": "12301.34",
"paymentAmountCurrencyCode": "USD"
}
]
}
 1. Create a new Project in Android Studio and name it as JSONObject Java Example.

2. Select API Level 19 and create project with an Empty MainActivity.java class and activity_main.xml file.

3. Go to AndroidManifest.xml file in the app > mainfest folder and use permission to access the internet.

<uses-permission android:name="android.permission.INTERNET" />

4. Now, go to activity_main.xml file and add a Textview Widget that with height and width that matches parent, code for this is here:

 <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

5. You can see complete code for activity_main.xml here:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.demo.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

6. Now go to MainActivity.java class and lets code some AsyncTask to fetch JSON data.

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        TextView tv=(TextView)findViewById(R.id.textView1);
     
 
        //Calling AsyncTask
        new JSONDataAsync().execute();
     
    }
 
public static class JSONDataAsync extends AsyncTask<String,Void,String>{


    @Override    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override    protected String doInBackground(String... strings) {
        
        OkHttpClient httpClient = new OkHttpClient();
        Request request= new Request.Builder()
                .url("https://www.jsonparser.com/1248dsdf43fdw3dwe3sdasca3")
                .build();

        try {
            Response response=httpClient.newCall(request).execute();
            assert response.body() != null;
            //data is returned to onPostExecute over here            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override    protected void onPostExecute(String s) {
        super.onPostExecute(s);
      
        try {
            JSONObject jsonObject = new JSONObject(s);
            if(jsonObject.has("items")){
            JSONArray jsonArray = jsonObject.getJSONArray("items");
            for(int i = 0; i < jsonArray.length(); i++ ){
                
                JSONObject items = jsonArray.getJSONObject(i);
                String payStatus = items.getString("id");
                String payAmt = items.getString("paymentAmount");
                String payCurr = items.getString("paymentAmountCurrencyCode");
 
                tv.setText(payStatus + " " + payAmt + " " + payCurr);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
 

Run the app and you will see TextView updated with JSONObject value. However, here the output will be the value of last JSONObject only because of for loop and more than one JSONObject and TextView can hold value of only one JSONObject.

To prevent this from happening you are advised to look for RecyclerView in Android!

Comments

Popular posts from this blog

How To Open PDF File in Android Application Example Included

Want to know How To Open PDF File in Android Application Example. To open a PDF File in Android Application, your app can take help from Free Android library available on Github.

Here are few apps made from PDF Library you can look at, click here to know more.

By using Android Library you are not only leveraging the hard work from another developer but also making it easier and quicker to develop an android app.
How To Open PDF File in Android Application Example  In this tutorial series, we will teach you how to open a pdf file in Android Application Example included with the help of Android PDFViewer library developed by Barteksc.

Get inspirtion from here: Top 7 PDF Download for Mobile Android Apps

Before I proceed further, here is the screenshot of the kind of PDF Viewer that’ll be created using Android Studio.



 How To Open PDF File in Android Application Example

The app will open a specified pdf file which will be copied in the assets folder of your Android studio project. I'v…

Python Turtle Example: Flappy Bird Development in under 10 mins!

Python Turtle Example | Develop Flappy Bird Clone in 10 mins In the following tutorial, we have used following Python libraries:
1. random: To generate obstacles at random position. 2. turtle: To help provide directions to the player. 3. vector from freegames: To 2-dimensional vectors.
Before developing the game, here is a screenshot of what you'll be developing in 10 mins.
Steps to create Python Flappy Bird Game:
1. Open Pycharm and install 'freegames' package by going to Files > Settings > Project Interpreter. 2. Click on '+' sign on right and search for 'freegames' package. 3. Import packages in your project by writing following lines of code:
from random import * from turtle import * from freegames import vector 4. There are two variables required in the game, one for Bird object and another for an array of obstacles:
bird = vector(0, 0) balls = []
5. Create function for the player response on screen tap:
def tap(x, y): "Move bird up in res…

Open Weather Map API Example | Create Android Weather App

In this tutorial blog, using open weather map API example, we will create an Android weather app. The Android App will able to access Open weather map website server and access weather details of particular location.

The App will look similar to the image shown below. It will fetch real time weather of the location provided in MainActivity.Java file.


Software / Files used:Android Studio (Version 3.x) Files Edited / Created:activity_main.xmlMainActivity.JavaWeather.JavaAndroidManifest.xml Steps Involved in Open Weather Map API Example: Here are the Steps you need to follow on ‘Open Weather map API Example’ to create Android Weather App:

1. Open the Open Weather map API link provided here. Sign up for Current Weather Data API key here.

2. Once the key is received, save it to notepad or on stick notes.

3. Open Android Studio and create a new Project with name, ‘FIMC Weather App’, we will select an empty activity in the wizard and wait for Gradle build.



4. Open AndroidManifest.xml…