30
JSON Introduction & Implementation in Java & Java Script Sreeni Inturi

Json demo

Embed Size (px)

Citation preview

Page 1: Json demo

JSON Introduction &

Implementation in Java & Java Script

Sreeni Inturi

Page 2: Json demo

Agenda:

• Introduction to JSON

•What is JSON

•Why JSON

• Implementation in Java

•Examples of JSON with Java

• JSON implementation with JavaScript

•Use in Ecommerce

Page 3: Json demo

JSON Intro & What is JSON • JSON stands for JavaScript Object Notation

• JSON is a lightweight text-based open standard data-

interchange format.

• It is entirely language independent and can be used with

most of the modern programming languages.

• JSON is derived from a subset of JavaScript

programming language (Standard ECMA-262 3rd

Edition—December 1999).

• The JSON format was originally specified by Douglas Crockford,

• JSON- The Fat Free Alternative to XML

• It is easy for humans to read and write. It is easy for machines to

parse and generate.

• A JSON string must be enclosed by double quotes.

• JSON files are saved with .json extension.

• Internet media type of JSON is "application/json".

Page 4: Json demo

JSON (cont.)

JSON is like XML because:

• They are both 'self-describing' meaning that values are named, and thus

'human readable'

• Both are hierarchical. (i.e. You can have values within values.)

• Both can be parsed and used by lots of programming languages

• Both can be passed around using AJAX (i.e. httpWebRequest)

JSON is Unlike XML because:

• XML uses angle brackets, with a tag name at the start and end of an

element: JSON uses squiggly brackets with the name only at the

beginning of the element.

• JSON is less verbose so it's definitely quicker for humans to write, and

probably quicker for us to read.

• JSON can be parsed trivially using the eval() procedure in JavaScript

• JSON includes arrays {where each element doesn't have a name of its

own}

• In XML you can use any name you want for an element, in JSON you

can't use reserved words from javascript

Page 5: Json demo

Why JSON Why JSON?

• For AJAX applications, JSON is faster and easier than XML:

Using XML

• Fetch an XML document

• Use the XML DOM to loop through the document

• Extract values and store in variables

Using JSON

• Fetch a JSON string

• eval() the JSON string

Why JSON ..

(1) Because JSON is easy to write. It is just like creating and accessing class

in javascript in object notation

(2) If you like HashTables, you will fall in love with JSON.

(3) JSON is just key : value pairs assigned within an object.

(4) JSON is very fast.

(5) It is easy to understand and can be integrated in any web application very

easily.

(6) Better organized data if prepared in well mannered way.

Page 6: Json demo

JSON Structure Data Structures supported by JSON:

JSON is built on two data structures

1) A collection of name/value pairs. • Different programming languages support this data

structure in different names. Like object, record, struct,

dictionary, hash table, keyed list, or associative array.

• e.g.: An object with three properties named "a", "b", and "c”

{ "a":1,"b":2,"c":3 }

2) An ordered list of values.

• In various programming languages, it is called as array,

vector, list, or sequence.

• e.g.: An array of three integers and one string value

[ 1, 2, 3, “four" ] Since data structure supported by JSON is also supported by most of the modern

programming languages, it makes JSON a very useful data-interchange format.

Page 7: Json demo

Data Types in JSON Object

• An object is an unordered set of name/value pairs

(it is unordered container for key/value pairs ).

• An object begins with { (left brace) and ends with

} (right brace).

• name/value pairs are separated by , (comma).

• Each name is followed by : (colon)

• keys and values or separated by colon

• Keys are strings

• Values are JSON values

– struct, record, hashtable, object

Page 8: Json demo

Object (cont..) Syntax

{ string : value, .......}

Examples:

{"name":"Jane Smith","grade":"A","level":3,

"format":{"type":"rect","width":1920, "height":1080,

"framerate":24}}

{

"name": "Jane Smith",

"grade": "A",

"format": {

"type": "rect",

"width": 1920,

"height": 1080,

"framerate": 24

}

}

{ : }valuestring

object

,

Page 9: Json demo

Array • Arrays are ordered sequences of values

• Arrays are wrapped in []

• Comma(,) separates values

• JSON does not talk about indexing.

– An implementation can start array indexing at 0 or 1.

Syntax:

[ value, .......]

Example:

["Sunday", "Monday", "Tuesday", "Wednesday",

"Thursday", "Friday", "Saturday"]

[ ]value

array

,

Page 10: Json demo

Array(cont.) If the JSON data describes an array, and each element of that array is an object.

[

{ "name": “Jane Smith",

"email": [email protected] },

{ "name": “Kathy Nauta",

"email": [email protected] }

]

Remember that even arrays can also be nested within an object. The following shows that.

{

"firstName": “Sam”, "lastName": “Williams",

"address":

{

"streetAddress": "1120 N Sterling Ave", "city": “Palatine", "state": “Illinois",“zip": “60067"

},

"phoneNumber":

[

{

"type": “work", "number": “8473157427"

},

{

"type": “cell", "number": “8472277906"

}

]

}

Page 11: Json demo

Data Type -Value Value:

• A value can be a string in double quotes, or a number, or

true or false or null, or an object or an array. These

structures can be nested.

number

string

value

object

false

null

array

true

Page 12: Json demo

Value - String String: A string is a sequence of zero or more Unicode characters,

enclosed by double quotes, using backslash escapes. A character is

represented as a single character string, similar to a C or Java string.

The following table shows supported string types.

String Types Description

" A double quotation mark.

\ Reverse Solidus

/ Solidus

b Backspace

f form feed

n newline

r Carriage return

t Horizontal tab

u Four hexadecimal digits

Page 13: Json demo

String(cont.)

• support string types in JSON

string

"Any UNICODE character except

" or \ or control character

\ "

\

quotation mark

reverse solidus

/solidus

bbackspace

formfeed

newline

carriage return

horizontal tab

4 hexadecimal digits

f

n

r

t

u

"

Page 14: Json demo

Data Type -Number Following are the supported number types

Number Types Description

Integer Positive or negative Digits.1-9. And 0.

Fraction Fractions like .8.

Exponent e, e+, e-, E, E+, E-

number

digit

1 - 9

.0

digit

e

E

digit

-

digit

+

-

Page 15: Json demo

Data Type –Boolean ,Whitespace Boolean values are

• true

• false

Whitespace

• Whitespace can be placed between any pair of supported data-types

Page 16: Json demo

JSON Java • JSON is a simple and easy to read and write data

exchange format. It’s popular and implemented in

countless projects worldwide, for those don’t like XML,

JSON is a very good alternative solution.

• There are many popular third party Java libraries to

process JSON data, which are Jackson, Google Gson,

JSON lib, XStream, JSON.simple, Argo, json-smart,

Flexjson, Stringtree etc.;

JSON-Lib:

• JSON-lib is a java library for that transforms beans,

collections, maps, java arrays and XML to JSON and

then for retransforming them back to beans, collections,

maps and others.

Page 17: Json demo

JSONObject import net.sf.json.JSONObject;

public class MyFirstJsonObject {

public static void main (String args[]) {

// create JSONObject instance

JSONObject object=new JSONObject();

// add name/value pairs

object.put("Name", "Sree");

object.put("Company", "Walgreens");

object.put("Dept","Ecommerce");

object.put("Team","Pharmacy");

object.put("City","Deerfield");

object.put("nickname","Sam");

System.out.println(object);

}

}

Following is the output:

{"Name":"Sree","Company":"Walgreens","Dept":"Ecommerce","Team":"Pharmacy",

"City":"Deerfield","nickname":"Sam"}

Page 18: Json demo

JSONArray package com.test;

import net.sf.json.JSONArray;

public class MyFirstJSONArray {

public static void main(String args[]) {

JSONArray jsonArray = new JSONArray();

jsonArray.add("one");

jsonArray.add(new Integer(2));

jsonArray.add(new Long(3));

jsonArray.add(new Double(4.26));

jsonArray.add(true);

jsonArray.add(new char [] { 'A', 'B', 'C' });

System.out.println(jsonArray.toString());

}

}

// following is the output:

["one", 2, 3, 4.26, true, ["A","B","C"]]

Page 19: Json demo

JSONString to Bean Create Department bean class with required attributes.

package com.test;

public class Department {

private String company;

private String deptName;

private String teamName;

private String mgrName;

public Department () { }

public Department (String company, String deptName, String teamName,String mgrName) {

this.company=company;

this.deptName=deptName;

this.teamName=teamName;

this.mgrName=mgrName;

}

// add getter/setters for all attributes

public String toString() {

return "Department [ " + "company = " + company + ", DeptName = " + deptName +

", TeamName = " + teamName + ", MgrName = " + mgrName + " ]"; }

}

}

Page 20: Json demo

JSONString to Bean (cont.) Get the JSONString and convert into Java Bean.

package com.test;

import net.sf.json.JSONObject;

import net.sf.json.JSONSerializer;

public class JsonStr2Bean {

public static void main(String[] args) {

String jsonString = "{" +

"company: 'Walgreens'," +

"deptName: 'Ecommerce'," + "teamName: 'Pharmacy'," +

"mgrName: 'Sachin Patel‘ " + "}";

// String to JSON

JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(jsonString);

System.out.println(jsonObj);

// JSON to BEAN

Department dept = (Department) JSONObject.toBean(jsonObj, Department.class);

System.out.println(dept.toString()); } }

// Following is the output:

{"company":"Walgreens","deptName":"Ecommerce","teamName":"Pharmacy","mgrName":"Sachin Patel"}

Department [ company = Walgreens, DeptName = Ecommerce, TeamName = Pharmacy,

MgrName = Sachin Patel ]

Page 21: Json demo

MedHelpJSONString to Bean (cont.) Get the MedHelp JSONString and convert into Java Bean.

package com.test;

import net.sf.json.JSONObject;

import net.sf.json.JSONSerializer;

public class MedHelpJsonStr2Bean {

public static void main(String[] args) {

String medHelpJsonStr =

"{\"email_name\":\"ban_warn_user\",\"to\":{\"id\":7,\"avatar_tn_url\":null,\"external_id\":12345,\"log

in\":\"uche\"},\"custom_message\":\"Your account has been disabled for violating the terms of

service.\",\"type\":\"ban\"}";

JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( medHelpJsonStr );

System.out.println(jsonObject);

BanWarn banWarn =(BanWarn) jsonObject.toBean( jsonObject, BanWarn.class);

System.out.println(banWarn);

// Following is the output:

{"email_name":"ban_warn_user","to":{"id":7,"avatar_tn_url":null,"external_id":12345,"login":"uche"},"custom_m

essage":"Your account has been disabled for violating the terms of service.","type":"ban"}

Ban Warn [ email_name = ban_warn_user, to = com.test.ToObject@253498, custom_message = Your

account has been disabled for violating the terms of service., type = ban ]

Page 22: Json demo

JSON in Java Script • JSON is a language independent text format which is fast and easy to

understand. That means it is really very simple and easy to learn without

sparing much time. In another words we can say that JSON is a lightweight

data-interchange format that is completely language independent but with

some conventions.

• we are going to discuss JSON with JavaScript.

• We can create objects in JSON with JavaScript in many ways :

• 1. "var JSONObjectName ={};" will create an empty object.

• 2. "var JSONObjectName= new Object();" will create a new

Object.

• 3. "var JSONObjectName = { "name ":“Bill", "age":23}; will

create an Object with attribute name which contains value in String

and age with numeric value.

• Now by creating this object we can access attributes by only "."

operator.

• Following is the full example code for creating an Object in

JavaScript using JSON:

Page 23: Json demo

JSON in Java Script example <html>

<head><title>Object creation in JSON in JavaScript</title>

<script language="javascript" >

var JSONObject = { "name" : "Sam", "address": "104 Wilmot Road", "floor" : 5,

"city" : "Deerfield", "phone":"8473157420" };

document.write("<h2><font color='blue'>Name</font>:" +JSONObject.name+"</h2>");

document.write("<h2><font color='blue'>Address</font>:" + JSONObject.address+"</h2>");

document.write("<h2><font color='blue'>Floor</font>:" + JSONObject.floor+"</h2>");

document.write("<h2><font color='blue'>City</font>:" + JSONObject.city+"</h2>");

document.write("<h2><font color='blue'>Phone No.</font>:" + JSONObject.phone+"</h2>");

</script>

</head>

<body><h3>Example of object creation in JSON in JavaScript</h3></body>

</html>

Page 24: Json demo

JSON in Java Script example (cont.) • Following is the output from previous slide of json – java script

Page 25: Json demo

JSON in Java Script (cont..) What is serialize and deserialize in Json-JavaScript

• With the context of working with JavaScript and JSON,

to get JSON value from JavaScript value is serialization

and when it's other way (JSON to JavaScript) is

deserialization.

• JavaScript JSON object

• The JavaScript JSON object comprises methods using

which you can convert JavaScript values to JSON format

and JSON notation to JavaScript values.

• We will now discuss two JSON methods - JSON.stringify

and JSON.parse.

• JSON.stringify

• JSON.stringify is used to convert JavaScript values to JSON.

• JSON.stringify example

Page 26: Json demo

Json-JavaScript convert Converting a JSON Text to a JavaScript Object

• One of the most common use of JSON is to fetch JSON data from a web

server (as a file or as an HttpRequest), convert the JSON data to a

JavaScript object, and then use the data in a web page.

• For simplicity, this can be demonstrated by using a string as input (instead

of a file).

• JSON Example - Object From String

• Create a JavaScript string containing JSON syntax:

var txt = '{ "employees" : [' +

'{ "firstName":"John" , "lastName":"Doe" },' +

'{ "firstName":"Anna" , "lastName":"Smith" },' +

‘{ "firstName":"Peter" , "lastName":"Jones" } ] }';

• Since JSON syntax is a subset of JavaScript syntax, the JavaScript function eval()

can be used to convert a JSON text into a JavaScript object.

• The eval() function uses the JavaScript compiler which will parse the JSON text and

produce a JavaScript object. The text must be wrapped in parenthesis to avoid a

syntax error:

• var obj = eval ("(" + txt + ")");

• Use the JavaScript object in our page:

Page 27: Json demo

Json Text convert into JavaScript Object(cont.) Example

<p>

First Name: <span id="fname"></span><br />

Last Name: <span id="lname"></span><br />

</p>

<script type="text/javascript">

document.getElementById("fname").innerHTML = obj.employees[1].firstName

document.getElementById("lname").innerHTML = obj.employees[1].lastName

</script>

Output of page is:

Create Object from JSON String

First Name: Anna

Last Name: Smith

Note: The eval() function can compile and execute any JavaScript. This represents a

potential security problem.

It is safer to use a JSON parser to convert a JSON text to a JavaScript object. A

JSON parser will recognize only JSON text and will not compile scripts.

Page 28: Json demo

Creating and Parsing JSON Messages with JavaScript

• creating message in JSON with JavaScript we have to include "json2.js"

file first. Message is then created by converting array object to string by

using the function "toJSONString()" .

• The toJSONString() functions for scalar types (like Number and Boolean)

are quite simple since they only need to return a string representation of the

instance value.

• The toJSONString() function for the Boolean type, for example, returns the

string "true" if the value is true, and "false" otherwise. • The toJSONString() functions for Array and Object types are more interesting. For Array

instances, the toJSONString() function for each contained element is called in sequence, with the

results being concatenated with commas to delimit each result. The final output enclosed in

square brackets. Likewise, for Object instances, each member is enumerated and its

toJSONString() function invoked. The member name and the JSON representation of its value

are concatenated with a colon in the middle; each member name and value pair is delimited with a

comma and the entire output is enclosed in curly brackets.

• We can parse the message with JSON in JavaScript by using the method

"String.parseJSON()".

• It parses the JSON message to an string or object. This method internally

uses the JavaScript's method eval() to parse messages.

Page 29: Json demo

JSON- Web Services • Recently a few XML experts have been claiming that the

decision made by large Web Service providers, like

Twitter and Foursquare, to drop XML from their Web

Services infrastructure is not very interesting news. They

also assert that the claims that JSON is more useful than

XML for the majority of Web Services is wishful thinking

by a “cadre of Web API designers” that have yet to

provide “richer APIs”.

Page 30: Json demo

Learn more about JSON

• http://www.json.org/java/

• http://www.w3schools.com/json/default.asp

• http://json-lib.sourceforge.net/

• http://digitalbazaar.com/2010/11/22/json-vs-

xml/

• http://techtracer.com/2007/04/01/json-web-

services-the-xml-json-debate-further-ahead/

• www.json.org/js.html

• https://developer.mozilla.org/en-

US/docs/JSON