JSON Object

Json object is an unordered set of names or values. Json object begins with Left braces ({) and end with right braces (}). Here each name is followed by colon (:) and the name or value pairs are separated by comma (,). Json provide native object support. Json method helps for converting values to Json and also helps for converting Json to values. Json stands for JavaScript Object Notation. Syntax of Json helps for serializing objects. The JSON does not support object references. The difference between Json object and other objects are

  1. Json object must be double quoted strings
  2. Trailing commas in objects
  3. Arrays are forbidden

The Json object includes some methods for parsing Json and converting values to Json. Properties of objects of Jsons are given below.

Properties inherited from Object:

constructor, __parent__, __proto__

Json Object key Methods

1) Parse: – Parse a string as JSON, optionally transform the produced value and its properties, and return the value. This method helps to convert string into a JavaScript object.

Syntax: –

var jsObject = JSON.parse(jsonString);

2) Stringify: – Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner. That is this method helps to convert a JavaScript object into a Json string.

Eg: –

var foo = {};
foo.bar = “new property”;
foo.baz = 3;
var jsonString = JSON.stringify(foo);

The below code is helps to activate corresponding browser, after creating the Json object. We are inserting these codes at the beginning of our code.

Syntax: –

if (!window.JSON) {
window.JSON = {
parse: function (sJSON) { return eval(“(“ + sJSON + “)”); },
stringify: function (vContent) {
if (vContent instanceof Object) {
var sOutput = ““;
if (vContent.constructor === Array) {
for (var nId = 0; nId < vContent.length; sOutput += this.stringify(vContent[nId]) + “,”, nId++);
return “[“ + sOutput.substr(0, sOutput.length - 1) + “]”;
}
if (vContent.toString !== Object.prototype.toString) {
return “\”“ + vContent.toString().replace(/”/g, “\\$&”) + “\”“; }
for (var sProp in vContent) { 
sOutput += “\”“ + sProp.replace(/”/g, “\\$&”) + “\”:” + this.stringify(vContent[sProp]) + “,”; }
return “{“ + sOutput.substr(0, sOutput.length - 1) + “}”;
}
return typeof vContent === “string” ? “\”“ + vContent.replace(/”/g, “\\$&”) + “\”“ : String(vContent);
}
};
}

The below two methods helps Gson is easy learn and implement.

1) toJson() – Convert Java object to JSON string format, and save it as “file.json”.

Eg: –

package com.site.core;
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
DataObject obj = new DataObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
try {
//write converted json data to a file named “file.json”
FileWriter writer = new FileWriter(“c:\\file.json”);
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(json);
}
}

Output

{“data1”:100,”data2”:”hello”,”list”:[“String 1”,”String 2”,”String 3”]}

2) fromJson() – Convert JSON into Java object

Eg: –

package com.site.core;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(
new FileReader(“c:\\file.json”));
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);
System.out.println(obj);
} catch (IOException e) {
e.printStackTrace();
} } }

Output

DataObject [data1=100, data2=hello, list=[String 1, String 2, String 3]]

Types of objects: –

1) public JSONObject (): – Creates a JSONObject with no name/value mappings.
2) public JSONObject (Map copyFrom): – Creates a new JSONObject by copying all name/value mappings from the given map.
3) public JSONObject (JSONTokener readFrom): – Creates a new JSONObject with name/value mappings from the next object in the tokener.
4) public JSONObject (String json): – Creates a new JSONObject with name/value mappings from the JSON string.
5) public JSONObject (JSONObject copyFrom, String[] names): – Creates a new JSONObject by copying mappings for the listed names from the given object. Names that aren’t present in copyFrom will be skipped.

Features of JSON

1) Gson Dependency: – For non-Maven user, get the Gson library from Gson official site for Maven user, declares following dependency in your pom.xml.

Syntax: –

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
</dependency>

2) POJO: – A pojo, with initialized values. Later use Gson to convert this object to/from JSON formatted string.

Eg: –

package com.site.core;
import java.util.ArrayList;
import java.util.List;
public class DataObject {
private int data1 = 100;
private String data2 = “hello”;
private List<String> list = new ArrayList<String>() {
{
add(“String 1”);
add(“String 2”);
add(“String 3”);
}
};
//getter and setter methods
@Override
public String toString() {
return “DataObject [data1=“ + data1 + “, data2=“ + data2 + “, list=“
+ list + “]”;
} }