3:11 pm - Sunday November 23, 6566

JSON Object With JAVA

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

JsonObject:

Json object holds key and value pairs.
It is an unordered collection of key and value pairs.
Key and values are separated by commas.
It supports any type of values (numeric, string, object, etc)

Syntax:

JSONObject object=new JSONObject();</pre>
object.put("key","value");

Another Format:

Its external form is a string wrapped in curly braces.

String json = "{"
 + " \"key\": \"value\", "
 + " \"key\": [ value1, value2 ] "
 + "}";
JSONObject ob=new JSONObject(json);

Methods:

Put-put method is used to store values in JsonObject.
opt-This method returns the value of the given key. If the given key does not exist it returns default value, null value.
get – This method returns value of given key. If the given key does not exist it throws an exception.
length – This method returns the length of the jsonObject. Values start from one.
isNull – This method returns whether the given key has null value.
has -This method used to find the whether the object has the given key.
append – This method is also used to add values into object.

Project Structure:

JARFILES: 

 

 

 

 

JObject.java:

package com.candidjava;

import java.util.Iterator;

import org.json.*;

public class JObject {
	public static void main(String args[]) throws JSONException {
		JSONObject object = new JSONObject();

		object.put("name", "Deepa");
		object.put("Reg No", new Integer(12345));
		object.put("Mark", new Double(99));
		object.put("mail", "deepa@ebullitent.com");
		object.put("City", "Chennai");

		int length = object.length();
		String opt = object.optString("name");
		boolean data = object.isNull("name");
		String getMark = object.getString("Mark");
		String getCity = (String) object.get("City");
		boolean mail = object.has("mail");
		// object.append("mark1","98");

		System.out.println(object);
		System.out.println("length: " + length);
		System.out.println("Name: " + opt);
		System.out.println("Is Null: " + data);
		System.out.println("city: " + getCity);
		System.out.println("has mail: " + mail);
		System.out.println("Mark:" + getMark);
		System.out.println("List of keys:");
		System.out.println("--------------");

		Iterator i = object.keys();
		while (i.hasNext()) {
			System.out.println(i.next());
		}
		object.toString();

	}
}

Output:

{“mail”:”deepa@ebullitent.com”,”Mark”:99,”name”:”Deepa”,”City”:”Chennai”,”Reg No”:12345}
length: 5
Name: Deepa
Is Null: false
city: Chennai
has mail: true
Mark:99.0
List of keys:
————–
mail
Mark
name
City
Reg No

DOWNLOAD+SOURCECODE

Filed in: Z-A JSON codes

Comments are closed.