JSON introduction and Java/Android tutorial

Introduction

JSON is an XML alternative. It is the communication and data exchange protocol, created mainly to use in JavaScript (JSON = JavaScript Object Notation), however it is also widely used in Java or Android apps to exchange data over the internet. Basic JSON message (JSONObject) consists of  key-value pairs, like this one:

Snippet 1:

{
	"userId":123,
	"firstName":"John",
	"lastName":"Doe",
	"isGoodProgrammer":1
}

JSON is fat-free, compared to XML, because there is significant difference in amount of metadata attached to message. Just compare XML to JSON message. This XML has exactly the same user data as JSON in the snippet above (more examples see here):

Snippet 2:

<user>
	<userId>123</userId>
	<firstName>John</firstName>
	<lastName>Doe</lastName>
	<isGoodProgrammer>1</isGoodProgrammer>
</user>

Java/Android tutorial
Android has built-in JSON utils, and for java, there is jar to include to application (for example json-org.jar). Add jar to Build path. Using JSON in Java code is the same for both: Android and Java.

Simple JSON Object

JSONObject is the simpliest key-value pair structure in JSON. Creating JSONObject like in Snippet 1 is done by this code:

JSONObject user = new JSONObject();
user.put("userId", 123);
user.put("firstName", "John");
user.put("lastName", "Doe");
user.put("isGoodProgrammer", true);

Reading value from JSONObject is done by:

int userId = user.getInt("userId");
String firstName = user.optString("firstName");

getString() – returns String containing firstName or throws JSONException if there was no object with key = “firstName”

optString() – returns String containing firstName or empty String (“”) if there was no object with key = “firstName”

Simple JSON Array of objects

Another structure is JSONArray. This is a set of JSONObjects (note that JSONArray is also a JSONobject). here is sample of Java code how to create JSONArray of users:

JSONObject user = new JSONObject();
user.put("userId", 123);
user.put("firstName", "John");
user.put("lastName", "Doe");
user.put("isGoodProgrammer", true);

JSONObject user2 = new JSONObject();
user2.put("userId", 456);
user2.put("firstName", "Erika");
user2.put("lastName", "Mellart");
user2.put("isGoodProgrammer", false);

JSONArray notebookUsers = new JSONArray();
notebookUsers.put(user);
notebookUsers.put(user2);

and the JSON message produced by this code is:

[
	{
		"lastName":"Doe",
		"userId":123,
		"isGoodProgrammer":true,
		"firstName":"John"
	},
	{
		"lastName":"Mellart",
		"userId":456,
		"isGoodProgrammer":false,
		"firstName":"Erika"
	}
]

(note that keys are not ordered as in Java code. Order does not matter)

Reading JSONObject from JSONArray is done by:

for (int i = 0; i<notebookUsers.length();i++) {
	JSONObject usr = notebookUsers.getJSONObject(i);
}

JSON features

1. JSONObjects and Arrays can be nested as many times as needed. JSONArray can be added to JSONObject as element with its id by:

JSONObject.put("key", new JSONArray);

2. JSONObject can be easily serialized to String in order to write to file or send over the Internet. The library also reads JSONObject from String (remember to handle JSONException, that is thrown when String input is not well formatted). See sample here:

JSONObject user = new JSONObject();
user.put("userId", 123);
String JsonString = user.toString();
JSONObject object = new JSONObject(JsonString);

3. There are utils that enables to convert Java objects, like Hashtables to JSON just by one line of code (see GSON).

Links and other tutorials

Creating & Parsing JSON data with Java
JSON in Android – Tutorial
JSON.simple example – Read and write JSON

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!

6 thoughts on “JSON introduction and Java/Android tutorial

  1. how about you get your data from sqlite databse and parse it to JSON to be sent later to the server? how do you iterate the id,name etc part here if you used arraylisthashmap in storing the data you get from database:

    [
    {
    “lastName”:”Doe”,
    “userId”:123,
    “isGoodProgrammer”:true,
    “firstName”:”John”
    },
    {
    “lastName”:”Mellart”,
    “userId”:456,
    “isGoodProgrammer”:false,
    “firstName”:”Erika”
    }
    ]

Give Your feedback: