JSON Parsing in Android for Beginners

 JSON Parsing in Android for Beginners



What is JSON?

  • JSON stands for JavaScript Object Notation.
  • In JSON information is stored in an organised and easy to access manner so it  is easily readable and understandable by humans.

Example:



  • Above code shows the format of JSON.
  • All the variables are stored in key and value pair for ex, from the above data “age” is key and “27” is a value.
  • By enclosing the variable’s value in curly braces, we’re indicating that the value is an object i.e data inside {} is object.
  • In the above data [ ] indicates an array.All the objects are stored with in an array.
  • we can access JSON data using an URL.In below example I am going to use this link “http://www.i2ce.in/reviews/1/1”.

How this program works:


  •  Initially we call AsyncTask from mainactivity.java with in that(asynctask) we establish a connection to communicate with the server.
  • Server will send the JSON data back to the Asynctask in mainactivity that data is stored temporarily in ratings.java by creating new objects for each rating.
  • JSON  data will be received by adapter by get method in Ratings.java and pass this data to the listview.
  • And our final listview will be like as shown in above image’s UI layout.
we have to add internet access permission in our manifest file.
step-2:
(use this step only if you get any errors while importing http libraries )
Add below line to gradle file after default configuration.
Add below dependencies into dependencies at the end of the gradle file.
finally your gradle file should look like this.
step-3:
we have to add a listview  in activity_main.xml.
step-4:
we have to create a layout contains some list of items which are display in activity-main’s listview.
step-5:
create a java class called reviews, declare required variables . create getters and setters for those variables as shown below.
step-6:
create reviewsadapter.java class and add below code into that
step-7:
open MainActivity.java and add below code.
Finally output should look like this: