Home  >  Core Java

Example of JSON Object in Java

By Arvind Rai, February 01, 2013
JSONObject is used to send and retreive data from server to client. JSON data has a format {"key":"value"}. From server data will be sent to UI in the JSON format. While creating JSONObject, we need to put key and value. There can be a JSON Array. The JSONArray data will look like {"res":[{"k20":"v20","k10":"v10"},{"k11":"v11","k21":"v21"},{"k22":"v22","k12":"v12"}]}. There must be a JSON contract between client and server.
JSONTest.java
package com.concretepage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONTest {
    public static void main(String... args) throws JSONException{
        final JSONObject res = new JSONObject();
        //adding value in JSON object
        JSONArray jarray= new JSONArray();
        for(int i=0;i<3;i++){
            JSONObject ob = new JSONObject();
            ob.put("k1"+i, "v1"+i);
            ob.put("k2"+i, "v2"+i);
            jarray.put(ob);
        }
        res.put("res", jarray);
        System.out.println("structure of created json object:"+res);
        //retrieving value from JSON object element wise
        System.out.println("retrieving value from JSON object element wise");
        JSONArray output= res.getJSONArray("res");
        for(int i=0;i<output.length();i++){
            JSONObject ob= output.getJSONObject(i);
            System.out.print(ob.get("k1"+i));
            System.out.println(ob.get("k2"+i));
        }
    }
}
Output
structure of created json object:{"res":[{"k20":"v20","k10":"v10"},{"k11":"v11","k21":"v21"},{"k22":"v22","k12":"v12"}]}
retrieving value from JSON object element wise
v10v20
v11v21
v12v22
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us