Json demo
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,009
On Slideshare
1,009
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
2
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. JSON Introduction &Implementation in Java & Java Script Sreeni Inturi
  • 2. Agenda:• Introduction to JSON• What is JSON• Why JSON• Implementation in Java• Examples of JSON with Java• JSON implementation with JavaScript• Use in Ecommerce
  • 3. 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".
  • 4. 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 its 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 doesnt have a name of its own}• In XML you can use any name you want for an element, in JSON you cant use reserved words from javascript
  • 5. 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 stringWhy JSON ..(1) Because JSON is easy to write. It is just like creating and accessing classin 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 veryeasily.(6) Better organized data if prepared in well mannered way.
  • 6. JSON StructureData Structures supported by JSON:JSON is built on two data structures1) 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 modernprogramming languages, it makes JSON a very useful data-interchange format.
  • 7. 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
  • 8. Object (cont..) Syntax { string : value, .......} object { 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 }}
  • 9. 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, .......] array [ value ] ,Example:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
  • 10. Array(cont.)If the JSON data describes an array, and each element of that array is an object. [ { "name": “Jane Smith", "email": jsmith@wag.com }, { "name": “Kathy Nauta", "email": knauta@wag.com }]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"}]}
  • 11. 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. value string number object array true false null
  • 12. 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
  • 13. String(cont.)• support string types in JSON string Any UNICODE character except " " " or or control character quotation mark " reverse solidus solidus / backspace b formfeed f newline n carriage return r horizontal tab t u 4 hexadecimal digits
  • 14. Data Type -NumberFollowing 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 0 . digit - digit e 1 - 9 digit E + digit -
  • 15. Data Type –Boolean ,Whitespace Boolean values are• true• false Whitespace• Whitespace can be placed between any pair of supported data-types
  • 16. 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.
  • 17. 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"}
  • 18. JSONArraypackage 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"]]
  • 19. JSONString to BeanCreate 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 + " ]"; } }}
  • 20. 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 ]
  • 21. 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,"login":"uche"},"custom_message":"Your account has been disabled for violating the terms ofservice.","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_message":"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 = Youraccount has been disabled for violating the terms of service., type = ban ]
  • 22. 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:
  • 23. 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>
  • 24. JSON in Java Script example (cont.)• Following is the output from previous slide of json – java script
  • 25. 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 its 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
  • 26. 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:
  • 27. 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].firstNamedocument.getElementById("lname").innerHTML = obj.employees[1].lastName</script>Output of page is:Create Object from JSON StringFirst Name: AnnaLast Name: SmithNote: The eval() function can compile and execute any JavaScript. This represents apotential security problem.It is safer to use a JSON parser to convert a JSON text to a JavaScript object. AJSON parser will recognize only JSON text and will not compile scripts.
  • 28. 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 JavaScripts method eval() to parse messages.
  • 29. 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”.
  • 30. 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