JavaScript Object Notation (JSON) is a format for data exchange and storage. JSON is simple and easy to parse information interchange format compared to xml. JSON format is widely used to exchange data between device and server in android apps.
In this tutorial, I’ll explain JSON, converting JSON string to java object and java object to JSON string using org json parser provided as a part of android sdk.
JSON elements are defined in curly braces { }. JSON element consists of name and value pair separated by colon and two elements are separated by comma. If an element contains more than one value (arrays), values are defined in braces [].
{"store" : "xyz ecommerce",
"maxCashback" : "20%",
"numCoupons" : "34",
"numDeals" : "12",
"coupons" : [ {"coupon" : "Get upto 10% off on shoes", "expiryDt" : "12/12/2020", "couponCode" : "MH34"},
{"coupon" : "Get Upto 80% off on mobiles", "expiryDt" : "02/04/2030", "couponCode" : "DH30"}],
"cashbackOffers" : ["10% cashback on electronics","20% cashback on fashion"]
}
Android sdk includes org.json JSON parsing library which offers JSONArray, JSONObject, JSONStringer, and JSONTokener classes using which JSON strings can be parsed and created.
JSONObject is the main class that can be instantiated passing json string to be parsed. It has several methods to get different types of data. For example, to get string type, you can call getString and to get array you can call getJSONArray.
For each data type, there are two methods, one starts with get and second one starts with opt. Get methods throw exception if data doesn’t exist. Whereas, opt methods returns either default value or fallback value passed to the methods.
package com.zoftino.androidui;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ActivityJSON extends AppCompatActivity {
private String TAG = ActivityJSON.class.getSimpleName();
private String jsonStr = "{\"store\" : \"xyz ecommerce\",\n" +
"\"maxCashback\" : \"Upto 20% cashback\",\n" +
"\"numCoupons\" : \"34 coupons\",\n" +
"\"coupons\" : [ {\"coupon\" : \"Get upto 10% off on shoes\", \"expiryDt\" : \"12/12/2020\", \"couponCode\" : \"MH34\"},\n" +
"\t{\"coupon\" : \"Get Upto 80% off on mobiles\", \"expiryDt\" : \"02/04/2030\", \"couponCode\" : \"DH30\"}],\n" +
"\"cashbackOffers\" : [\"10% cashback on electronics\",\"20% cashback on fashion\"]\n" +
"}”;
private TextView storeTv;
private TextView numCouponsTv;
private TextView maxCashbackTv;
private TextView couponsTv;
private TextView cashbackTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.json);
Log.d(TAG, "set activity content view in onCreate");
storeTv = (TextView)findViewById(R.id.store);
numCouponsTv = (TextView)findViewById(R.id.numCoupons);
maxCashbackTv = (TextView)findViewById(R.id.maxCashback);
couponsTv = (TextView)findViewById(R.id.allcoupons);
cashbackTv = (TextView)findViewById(R.id.cashbackOffers);
//execute getting json response over http and parsing json response in background thread
// for this example, json string is passed to async task instead of getting it from server
new GetStoreData().execute(jsonStr);
}
private class GetStoreData extends AsyncTask<String, Void, Store> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Store doInBackground(String... params) {
Store store = new Store();
String storeDataJson;
storeDataJson = params[0];
Log.e(TAG, "Json string : " + storeDataJson);
try {
//create JSONObject passing json string
JSONObject jsonObj = new JSONObject(storeDataJson);
//get store name passing store name key
String storeName = jsonObj.optString("store");
store.setStore(storeName);
//get num of coupons from jsonobject
String numCoupons = jsonObj.optString("numCoupons");
store.setNumCoupons(numCoupons);
//get max coupons from jsonobject
String maxCashback = jsonObj.optString("maxCashback");
store.setMaxCashback(maxCashback);
//get coupons data, first get coupons jsonarray from jsonobject
JSONArray couponsArray = jsonObj.getJSONArray("coupons");
String couponsData = "";
for(int i=0; i < couponsArray.length(); i++){
JSONObject jsonObject = couponsArray.getJSONObject(i);
couponsData = couponsData+ " "+jsonObject.getString("coupon");
couponsData = couponsData+ " "+jsonObject.getString("expiryDt");
couponsData = couponsData+ " "+jsonObject.getString("couponCode");
couponsData = couponsData+ " \n";
}
store.setCoupons(couponsData);
//get cashback data, first get cashback jsonarray from jsonobject
JSONArray cashbackArray = jsonObj.getJSONArray("cashbackOffers");
String cashbackData = "";
for(int i=0; i < cashbackArray.length(); i++){
String cb = cashbackArray.getString(i);
cashbackData = cashbackData+ " "+cb;
cashbackData = cashbackData+ " \n";
}
store.setCashbackoffers(cashbackData);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing exception: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Could not get store and coupons data",
Toast.LENGTH_LONG).show();
}
});
}
return store;
}
@Override
protected void onPostExecute(Store result) {
super.onPostExecute(result);
Log.e(TAG, "setting ui values");
storeTv.setText(result.getStore());
numCouponsTv.setText(result.getNumCoupons());
maxCashbackTv.setText(result.getMaxCashback());
couponsTv.setText(result.getCoupons());
cashbackTv.setText(result.getCashbackoffers());
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<TextView
android:id="@+id/store"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"></TextView>
<TextView
android:id="@+id/numCoupons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="29dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="15dp"
app:layout_constraintTop_toBottomOf="@+id/store"></TextView>
<TextView
android:id="@+id/maxCashback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toRightOf="@+id/numCoupons"
android:layout_marginLeft="8dp"
android:layout_marginTop="15dp"
app:layout_constraintTop_toBottomOf="@+id/store"
app:layout_constraintHorizontal_bias="0.78"></TextView>
<TextView
android:id="@+id/coupons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="COUPONS"
android:textSize="25dp"
android:layout_marginTop="32dp"
app:layout_constraintTop_toBottomOf="@+id/numCoupons"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"></TextView>
<TextView
android:id="@+id/allcoupons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@+id/coupons"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"></TextView>
<TextView
android:id="@+id/cashback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CASHBACK"
android:textSize="25dp"
android:layout_marginTop="32dp"
app:layout_constraintTop_toBottomOf="@+id/allcoupons"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"></TextView>
<TextView
android:id="@+id/cashbackOffers"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@+id/cashback"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"></TextView>
</android.support.constraint.ConstraintLayout>
You can create JSON string using org json library. To create JSON string, first you need to create json object and add elements. To add arrays, use JSONArray class. Below code creates example json string provided above.
public String createJsonObject(){
//to create json string, create JSONObject and add elements
try {
JSONObject store = new JSONObject();
store.put("store", "abc ecommerce store");
store.put("maxCashback", "Upto 13% cashback");
store.put("numCoupons", "55 coupons");
// create json array for coupons
JSONArray coupons = new JSONArray();
//create JSONOjbect for coupon one and set all elements of coupon
JSONObject couponOne = new JSONObject();
couponOne.put("coupon", "Get upto 10% off on shoes");
couponOne.put("expiryDt", "12/12/2017");
couponOne.put("couponCode", "UYU");
coupons.put(couponOne);
//create JSONOjbect for coupon two and set all elements of coupon
JSONObject couponTwo = new JSONObject();
couponOne.put("coupon", "Get upto 30% off on electronics");
couponOne.put("expiryDt", "06/12/2020");
couponOne.put("couponCode", "HY7");
coupons.put(couponTwo);
//add coupon JSONArray to store JSONObject
store.put("coupons", coupons);
//create cashback offer json array
JSONArray cashbackOffers = new JSONArray();
//add cashback offers to array
cashbackOffers.put("Upto 12% cashback on appliances");
cashbackOffers.put("Upto 8% cashback on mobiles");
//add cashback array to store json object
store.put("cashbackOffers", cashbackOffers);
//convert json object to json string
return store.toString();
} catch (JSONException e) {
}
return "";
}