SlideShare a Scribd company logo
#127
   Get More Refcardz! Visit refcardz.com




                                                                                       Getting Started with
                                           CONTENTS INCLUDE:
                                           n	
                                                Whats New in JPA 2.0



                                                                                                               JPA 2.0
                                           n	
                                                JDBC Properties
                                           n	
                                                Access Mode
                                           n	
                                                Mappings
                                           n	
                                                Shared Cache
                                           n	
                                                Additional API and more...                                      By Mike Keith
Getting Started with JPA 2.0




                                                                             DZone, Inc.   |   www.dzone.com
#173
Get More Refcardz! Visit refcardz.com



                                        CONTENTS INCLUDE:
                                        ❱ JSON Validation
                                        ❱ JSON Modeling
                                        ❱ JSON in the Browser
                                                                                                                                                                Core JSON
                                        ❱ JSON and Ajax                                                                                   The Fat-Free Alternative to XML
                                        ❱ JSON and Java
                                        ❱ JSON and Ruby...and More!                                                                                                                       By Tom Marrs


                                                                                                                            An Object (in this case address) consists of comma-separated name/
                                             JSON OVERVIEW                                                                  value pairs surrounded by curly braces.

                                        JSON (JavaScript Object Notation) is a standard text-based data
                                        interchange format that enables applications to exchange data over a                Array
                                        computer network. Programs written in Ruby, Java/EE, JavaScript, C#/.               An Array is a collection of ordered values, and looks like this:
                                        Net, PHP, etc. can easily consume and produce JSON data because it is
                                        independent of languages and computing platforms. The abundance of                    {
                                        JSON-related APIs and tools make it easy to use JSON from your favorite                    “people” : [
                                                                                                                                     { “firstName”: “John”, “lastName”: “Smith”, “age”: 35 },
                                        programming language, IDE, and runtime environment. Additionlly, popular
                                                                                                                                     { “firstName”: “Jane”, “lastName”: “Smith”, “age”: 32 }
                                        NoSQL databases such as MongoDB and CouchBase are based on JSON.                           ]
                                                                                                                              }
                                        JSON was created by Douglas Crockford in 2001, and is specified in RFC
                                        4627 with the IETF (Internet Engineering Task Force) standard; see http://
                                        tools.ietf.org/html/rfc4627. Per the specification, the JSON’s IANA (Internet       Value Types
                                        Assigned Numbers Authority) media type is application/json, and the                 A Value (i.e., the right-hand side of a Name/Value Pair) can be one of the
                                        file type is                                                                        following:
                                        .json.
                                                                                                                                  •	   Object
                                        What is JSON?                                                                             •	   Array
                                        JSON is a simple data format, and has 3 basic data structures:                            •	   String
                                             •	 Name/Value (or Key/Value) Pair.                                                   •	   Number
                                             •	 Object.                                                                           •	   Boolean
                                             •	 Arrays.                                                                           •	   null

                                        A valid JSON document is always surrounded with curly braces, like this:            Number
                                                                                                                            A number can be an integer or double-precision float. Here are some
                                         { JSON-Data }                                                                      examples:

                                        Please note that some members of the JSON community use the term                      “age”: 29
                                        “string” rather than “document.”                                                      “cost”: 299.99
                                                                                                                              “temperature”: -10.5
                                                                                                                              “speed_of_light”: 1.23e11
                                        Why JSON?                                                                             “speed_of_light”: 1.23e+11
                                        JSON is gradually replacing XML as the preferred data exchange format                 “speed_of_light”: 1.23E11
                                        on the internet because JSON is easy to read and its structures map to                “speed_of_light”: 1.23E+11
                                        common programming concepts such as Objects and Arrays. JSON is
                                        more efficient (i.e., faster parsing and network transmission) than XML
                                        because JSON is more compact—there are no begin and end tags.                       The property name (i.e., age, etc.) is a string surrounded by double quotes,
                                                                                                                            but the value does not have quotes. A number can be prefixed by a minus
                                        Name/Value Pair                                                                     sign. The exponent portion (denoted by e or E) comes after the number
                                        A Name/Value pair looks like this:                                                  value, and can have an optional plus or minus sign. Neither leading zeroes,
                                                                                                                            octal, nor hexadecimal values are allowed.
                                         {
                                             “firstName”: “John”
                                         }


                                        A property name (i.e., firstName) is a string that is surrounded by double
                                        quotes. A value can be a string (as in the above example), but this is just
                                        one of several valid data types. (Please see the Data Types section for
                                        further details.) Some well-known technologies claim that they use JSON
                                        data formats, but they don’t surround their strings with quotes. However,
                                        this is not valid JSON; see the JSON Validation section.

                                        Object
                                        An Object is a collection of unordered Name/Value pairs. The following
                                        example shows an address object:

                                         {
Core JSON




                                             “address” : {
                                               “line1” : “555 Main Street”,
                                               “city” : “Denver”,
                                               “stateOrProvince” : “CO”,
                                               “zipOrPostalCode” : “80202”,
                                               “country” : “USA”
                                             }
                                         }



                                                                                                         DZone, Inc.    |   www.dzone.com
2                                                                   Core JSON




Boolean
A Boolean in JSON can either be true or false, as follows:

 {
     “emailValidated” : true
 }


The property name (emailValid) is a string surrounded by double
quotes, but the value (true) does not have quotes.

null
Although technically not a data type, null is a special value to indicate that
a data element has no value. In the following example, the age field has no
value (possibly because the user chose not to enter this information):

 {
     “age” : null
 }                                                                                    JSONLint is also available as a Chrome extension in the Chrome Web Store.


Comments                                                                                JSON MODELING
JSON does not allow comments. Comments were originally a part of JSON,
but developers misused them by putting parsing directives in comments.                Developing valid JSON documents for real applications can be tedious and
When Douglas Crockford saw this practice, he removed comments from                    error-prone. To avoid typographical errors, you can use JSONPad, JSON
JSON to preserve interoperability between computing platforms.                        Editor Online, and JSON Designer to create a logical model (similar to UML)
                                                                                      and generate valid JSON documents.
Style
You’ve probably noticed that the property names (i.e., the name on the left-          JSONPad
hand side of the colon) use camel case. This is not a rule or standard, but           JSONPad (from http://www.jsonpad.com/en/Home.html) is a GUI tool
is a convention prescribed in Google’s JSON Style Guide at: http://google-            that eliminates typing JSON text by providing an interface that enables you
styleguide.googlecode.com/svn/trunk/jsoncstyleguide.xml.                              to create Objects, Keys (i.e., Name/Value Pairs), and Arrays. JSONPad is
                                                                                      available as a Windows or Mac GUI, and online at the JSONPad web site.
Official Syntax                                                                       To create a model, use the green plus key under the text area. The following
Douglas Crockford’s JSON site (http://www.json.org) provides a full                   data types are supported: Key (i.e., Name/Value Pair), Object, and Array.
description of JSON syntax.                                                           After the model is complete, press the blue up-arrow button (under the
                                                                                      Tree tab) to generate a valid, pretty-printed JSON document based on the
Additionally, the JSON Pro Quick Guide (freely available in the iPhone App            model:
Store) provides examples and an overview of JSON syntax.


     JSON VALIDATION

A textual document MUST follow the JSON syntax rules to be considered
a valid JSON document. Valid JSON is important because it ensures
interoperability between applications and JSON-related tools. Although
the JSON.org web site shows JSON syntax, sometimes it’s easier to see
JSON validation in action. JSONLint (http://www.jsonlint.com) provides an
interactive, web-based JSON validator. To use it, type or paste some text
into the main text area and press the Validate button. If the text isn’t valid
JSON, you’ll see an error message as follows:




                                                                                      The end result is a valid JSON document that is usable in your application.
                                                                                      You can also generate a model by pasting JSON text into the text area and
                                                                                      pressing the green down arrow in the Tree tab. Under the Format tab, you
                                                                                      can either compress or pretty print a JSON document. JSONPad validates
                                                                                      the JSON document in the text are when you press the JSON button in the
                                                                                      Tools tab.

                                                                                      JSON Editor Online
                                                                                      JSON Editor Online (http://jsoneditoronline.org/) is an online JSON modeler,
In this case, the property name for the address Object is missing a                   and is also available as a Chrome extension.
closing double quote. After you fix this problem and press the Validate
button, JSONLint pretty-prints the JSON document as follows:
                                                                                        JSON IN THE BROWSER

                                                                                      Firefox and Chrome provide excellent extensions (i.e., add-ons and plugins)
                                                                                      that make it easier to work with JSON.


                                                                    DZone, Inc.   |   www.dzone.com
3                                                                    Core JSON




REST Client                                                                         The JSONView Chrome extension provides a bit more functionality than its
Rest Client is a Firefox extension that provides the ability to debug and           Firefox counterpart – it enables a user to search a JSON document using
test RESTful Web Services from the browser. The ability to test from the            the JSONQuery language. For example, entering ..bib_key in the Query
browser isn’t new, but the output formatting is much more readable.                 text box displays all the bib_key fields in the text:




The above example uses the Books service from the Open Library API.                 JSONQuery is one of several technologies that can search JSON
After entering the service URI, the Response Body (Highlight) tab shows the         documents and return the desired element(s).
JSON output.
                                                                                    JSON Beautification with JSON SH
Pretty Printing with JSONView                                                       JSON SH is a Chrome extension (available in the Google Chrome Web
JSON is not very readable when displayed natively in a browser. JSONView            Store) that acts as a pretty-printer and a validator. Paste a valid (but not
is a Firefox and Chrome extension that pretty-prints JSON.                          pretty) JSON document into the text area at the top of the page, and JSON
                                                                                    SH beautifies the text into a human-readable format.
JSONView in Firefox
After installing this extension and re-starting Firefox, the JSON response
                                                                                         JSON AND AJAX
from the Open Library Books service URI is readable, and you can expand/
collapse objects on the page:
                                                                                    AJAX (Asynchronous JavaScript and XML) was one of the original use
                                                                                    cases for JSON, and the following jQuery example shows how a JavaScript
                                                                                    client makes an HTTP Get request to a RESTful Web Service and processes
                                                                                    a JSON response:

                                                                                     $.getJSON(‘http://example/service/addresses/home/1’,
                                                                                       function(data) {
                                                                                         var address = JSON.parse(data);

                                                                                             console.log(“Address Line 1 = “ + address.line1);
                                                                                         }
                                                                                     );


                                                                                    In the code above, $.getJSON() (a shorthand version of the main
                                                                                    jQuery $.ajax() call) makes an HTTP GET request. The (anonymous)
                                                                                    success callback function receives the JSON response and parses it into
                                                                                    a JavaScript object using JSON.parse(), which is part of the ECMA-
                                                                                    262 standard (beginning with the 5th edition) – please see http://www.
                                                                                    ecmascript.org/ for further information). The console.log() method
JSONView in Chrome                                                                  then logs line 1 of the address to the browser console. Conversely, the
JSONView is also available as a Chrome extension from the Chrome Web                JSON.stringify() method converts a JavaScript value to a JSON string
Store:                                                                              (with optional pretty-printing).


                                                                                         JSON AND JAVA

                                                                                    The Jackson (http://jackson.codehaus.org/) library is a popular Java-based
                                                                                    JSON API. Here’s an example of how to marshal/unmarshal an Address
                                                                                    object to/from JSON:

                                                                                     import java.io.Writer;
                                                                                     import java.io.StringWriter;
                                                                                     import org.codehaus.jackson.map.ObjectMapper;

                                                                                     public class Address {
                                                                                         private String line1;
                                                                                         private String city;
                                                                                         private String stateOrProvince;
                                                                                         private String zipOrPostalCode;
                                                                                         private String country;

                                                                                             public Address() {}
                                                                                     	
                                                                                             public String getLine1() {
Click on the minus sign to collapse each element, and press the Toggle                           return line1;
Collapsed link to show/hide each collapsed element.                                          }			                      <!---Snippet con’t on next page-->



                                                                  DZone, Inc.   |   www.dzone.com
4                                                                       Core JSON




       public void setLine1(line1) {                                               The JSON gem’s to_json method converts a String or Hash to JSON. The
          this.line1 = line1;                                                      Address object’s to_json method converts an Address to JSON format
       }                                                                           by converting its data members to a Hash and then calling to to_json on
 	
                                                                                   the Hash. To convert the Address to JSON, do the following:
       // Remaining getters and setters ...
 }
                                                                                    addr1 = Address.new(‘555 Main Street’, ‘Denver’, ‘CO’, ‘80231’,
 Address addrOut = new Address();                                                   ‘US’)
 // Call setters to populate addrOut …                                              puts addr1.to_json
 ObjectMapper mapper = new ObjectMapper(); // Reuse this.                           # Outputs the following …
                                                                                    {“line1”:”555 Main Street”,”city”:”Denver”,”state_or_
 // Marshal Address object to JSON String.                                          province”:”CO”,”zip_or_postal_code”:”80231”,”country”:”US”}
 Writer writer = new StringWriter();
 mapper.writeValue(writer, addrOut);
 System.out.println(writer.toString());
                                                                                   The JSON gem’s JSON.parse method converts a JSON String to a Hash.
 // Unmarshal Address object from JSON String.                                     The Address object’s from_json! method takes a JSON String, calls
 String addrJsonStr =                                                              JSON.parse to convert to a Hash, and sets each corresponding data
 “{“ +                                                                             member from the Hash as follows:
      “”address” : {“ +
      “”line1” : ”555 Main Street”,” +
      “”city” : ”Denver”,”                                                      json_addr = <<END
      “”stateOrProvince” : ”CO”,”                                               {
      “”zipOrPostalCode” : ”80202”,” +                                            “line1” : “999 Broadway”, “city” : “Anytown”,
      “”country” : ”USA”” +                                                       “state_or_province” : “CA”, “zip_or_postal_code” : “90210”,
      “}” +                                                                           “country” : “USA”
 “}”;                                                                               }
                                                                                    END
 Address addrIn = mapper.readValue(addrJsonStr, Address.class);
                                                                                    addr2 = Address.new
                                                                                    addr2.from_json!(json_addr)
In addition to Jackson, other well-known Java-based JSON APIs include:
                                                                                   In addition to the JSON gem, other JSON-related gems include:
 API                        Source
 Google GSON                http://code.google.com/p/google-json/                   API                          Source
                                                                                    ActiveSupport JSON           http://api.rubyonrails.org/classes/
 SOJO                       http://sojo.sourceforge.net/
                                                                                                                 ActiveSupport/JSON.html
 org.json (by Douglas       http://www.json.org/java
                                                                                    Yajl                         https://github.com/brianmario/yajl-ruby
 Crockford)
                                                                                    Oj                           https://github.com/ohler55/oj
 json-lib                   http://sourceforge.net/projects/json-lib/
 json-io                    http://code.google.com/p/json-io
                                                                                     JSON AND RUBY ON RAILS
 jsontools                  http://jsontools.berlios.de/
 jsonbeans                  http://code.google.com/p/jsonbeans/                    Ruby on Rails provides additional functionality that makes it easier
                                                                                   to convert Ruby objects to JSON. The following controller uses the
                                                                                   ActionController’s render method to output an Address object to JSON:
     JSON AND RUBY
                                                                                    class Person
There are many JSON-related libraries for Ruby. Here’s an example using               attr_accessor :first_name, :last_name
the JSON gem that comes standard with Ruby.
                                                                                      def initialize(first_name=nil, last_name=nil)
                                                                                        @first_name = first_name
 require ‘json’                                                                         @last_name = last_name
                                                                                      end
 class Address                                                                      end

     attr_accessor :line1, :city, :state_or_province,                               class MyController < ApplicationController
                   :zip_or_postal_code, :country                                      def index
                                                                                        person = Person.new(‘John’, ‘Doe’)
     def initialize(line1=’’, city=’’, state_or_province=’’,                            respond_to do |format|
                    zip_or_postal_code=’’, country=’’)                                    format.html # index.html.erb
       @line1 = line1                                                                     format.json { render :json => person}
       @city = city                                                                     end
       @state_or_province = state_or_province                                         end
       @zip_or_postal_code = zip_or_postal_code                                     end
       @country = country
     end
                                                                                   The Rails ApplicationController takes care of marshalling/
     def to_json                                                                   unmarshalling objects to/from JSON, so there’s no need to write a to_
       to_hash.to_json
     end
                                                                                   json method here.

     def from_json!(str)
       JSON.parse(str).each { |var, val| send(“#{var}=”, val) }                      JSON SCHEMA
     end

     private                                                                       JSON Schema specifies the structure of a JSON document. JSON Schema
                                                                                   can be used to validate the content of JSON sent to/received from a
   def to_hash                                                                     RESTful Web Service. JSON Schemas are written in JSON.
     Hash[instance_variables.map { |var| [var[1..-1].to_sym,
          send(var[1..-1])] }]                                                     The main JSON Schema site can be found at: http://json-schema.org.
   end
                                                                                   JSON Schema is a work in progress – the JSON Schema team has just
 end
                                                                                   published version 0.4, which can be found at: http://tools.ietf.org/html/
                                                                                   draft-zyp-json-schema-04.

                                                                                   Some important JSON Schema constructs include:


                                                                 DZone, Inc.   |   www.dzone.com
5                                                                     Core JSON




 Construct Description                                                                                                         “phoneNumber”: {
                                                                                                                                   “type”: “object”,
 type           The data type object, array, string, number, etc.                                                                  “id”: “phoneNumber”,
                                                                                                                                   “required”: true,
 $schema        The URI that provides the schema version.                                                                          “properties”: {
 required       true/false                                                                                                             “channel”: {
                                                                                                                                           “type”: “string”,
 id             Data element id                                                                                                            “id”: “channel”,
                                                                                                                                           “required”: true,
 properties     Validation properties for a data element include type (see                                                                 “enum”: [
                above), minimum (minimum value), maximum (maximum                                                                               “cell”,
                                                                                                                                                “work”,
                value), enum, etc.                                                                                                              “home”
                                                                                                                                           ]
Here is a sample JSON Schema for a portion of an online gift registry:                                                                 },
                                                                                                                                       “number”: {
  “type”: “object”,                                                                                                                        “type”: “string”,
  “$schema”: “http://json-schema.org/draft-03/schema”,                                                                                     “id”: “number”,
  “id”: “#”,                                                                                                                               “required”: true
  “required”: true,                                                                                                                    }
  “properties”: {                                                                                                                  }
      “registrants”: {                                                                                                         }
          “type”: “array”,                                                                                                 }
          “id”: “registrants”,                                                                                         }
          “required”: true,                                                                                        }
          “items”: {                                                                                          }
              “type”: “object”,                                                                         }
              “required”: false,
              “properties”: {
                  “address”: {                                                                        The above schema:
                       “type”: “object”,
                       “id”: “address”,
                       “required”: true,                                                                    •	 Requires an array of registrant objects.
                       “properties”: {                                                                      •	 Limits the phoneNumber.channel field to the following values:
                           “city”: {                                                                           cell, work, fax, or home.
                                “type”: “string”,
                                                                                                            •	 Limits the address.premise field to these values: home, work, or
                                “id”: “city”,
                                “required”: true                                                               other.
                           },
                           “country”: {                                                               A Web Service consumer could use this schema to validate the following
                                “type”: “string”,
                                                                                                      JSON document:
                                “id”: “country”,
                                “required”: false
                           },
                                                                                                        {
                           “line1”: {
                                                                                                              “registrants”: [
                                “type”: “string”,
                                                                                                                  {
                                “id”: “line1”,
                                                                                                                      “firstName”: “Fred”,
                                “required”: true
                                                                                                                      “lastName”: “Smith”,
                           },
                                                                                                                      “phoneNumber”: {
                           “line2”: {
                                                                                                                           “channel”: “cell”,
                                “type”: “string”,
                                                                                                                           “number”: “303-555-1212”
                                “id”: “line2”,
                                                                                                                      },
                                “required”: false
                                                                                                                      “address”: {
                           },
                                                                                                                           “premise”: “home”,
                           “postalCode”: {
                                                                                                                           “line1”: “555 Broadway NW”,
                                “type”: “string”,
                                                                                                                           “line2”: “# 000”,
                                “id”: “postalCode”,
                                                                                                                           “city”: “Denver”,
                                “required”: true
                                                                                                                           “stateOrProvince”: “CO”,
                           },
                                                                                                                           “postalCode”: “88888”,
                           “premise”: {
                                                                                                                           “country”: “USA”
                                “type”: “string”,
                                                                                                                      }
                                “id”: “premise”,
                                                                                                                  }
                                “required”: true,
                                                                                                              ]
                                “enum”: [
                                                                                                        }
                                    “work”,
                                    “home”,
                                    “other”
                                ]
                           },                                                                         JSON Schema Generator
                           “stateOrProvince”: {                                                       Creating a JSON Schema is tedious and error-prone. Use a JSON Schema
                                “type”: “string”,                                                     Generator to generate a Schema from any valid JSON document. Visit the
                                “id”: “stateOrProvince”,                                              online JSON Schema Generator (www.jsonschema.net/) and generate a
                                “required”: true
                           }                                                                          schema by doing the following:
                       }
                  },                                                                                        •	 Paste the JSON document into the right-hand text area.
 		               “firstName”: {                                                                            •	 Choose the JSON Input option
                       “type”: “string”,
                       “id”: “firstName”,                                                                   •	 Press the Generate Schema button.
                       “required”: true
                  },
                  “lastName”: {
                                                                                                      JSON Schema Validator
                       “type”: “string”,                                                              An application uses a JSON Schema Validator to ensure that a JSON
                       “id”: “lastName”,                                                              document conforms to the structure specified by the Schema. JSON
                       “required”: true                                                               Schema Validators are available for most modern programming languages:
                  },


                                                                                                       JSON Schema             Language       Source
                                                                                                       Validator
                                                                                                       JSV                     JavaScript     https://github.com/garycourt/JSV
                                                                                                       Ruby JSON Schema        Ruby           https://github.com/hoxworth/json-
 			                                <!============Snippet con’t on next page------------------>
                                                                                                       Validator                              schema



                                                                                  DZone, Inc.     |   www.dzone.com
6                                                                 Core JSON




         JSON Schema                      Language                 Source
         Validator
         json-schema-                     Java                     https://github.com/fge/json-
         validator                                                 schema-validator
         php-json-schema                  PHP                      https://github.com/hasbridge/php-
         (by MIT)                                                  json-schema
         JSON.Net                         .NET                     http://james.newtonking.com/
                                                                   projects/json-net.aspx

       Besides the language-specific tools, there is an excellent online JSON
       Schema Validator at: http://json-schema-validator.herokuapp.com. To use
       this site, enter the JSON document and Schema into the corresponding text
       boxes and press the Validate button.

           IN CONCLUSION

       We’ve covered the basics of JSON, but we’ve just scratched the surface.
       Although JSON is a simple data format, there are many tools to streamline
       the design and development process. JSON is a standard, it has replaced
       XML as the preferred data interchange format on the Internet, and it
       enables developers to create efficient, interoperable enterprise-class
       applications.




    ABOUT THE AUTHORS                                                                                                        RECOMMENDED BOOK
                                    Tom Marrs is a Principal Architect at Ciber, where he                                                      With JavaScript: The Good Parts, you’ll discover a
                                    specializes in Service-Oriented Architecture (SOA) He                                                      beautiful, elegant, lightweight and highly expressive
                                    designs and implements mission-critical web and                                                            language that lets you create effective code, whether
                                    business applications using the latest SOA, Ruby on                                                        you’re managing object libraries or just trying to get
                                    Rails, REST, HTML5, JavaScript, Java/EE, and Open                                                          Ajax to run fast. If you develop sites or applications for
                                    Source technologies. Tom is also the author of the                                                         the Web, this book is an absolute must.
                                    upcoming JSON at Work, and a founder of the Denver
                                    Open Source User Group (DOSUG)
                                                                                                                                               Buy Here.




                                                                   Browse our collection of over 150 Free Cheat Sheets
                                                                                                                                                                    Upcoming Refcardz


                                                                                                         Free PDF
                                                                                                                                                                    Debugging Patterns
                                                                                                                                                                    Clean Code
                                                                                                                                                                    Cypher
                                                                                                                                                                    Object-Oriented JS


                                                                                                                         DZone, Inc.
                                                                                                                         150 Preston Executive Dr.
                                                                                                                         Suite 201
                                                                                                                         Cary, NC 27513
DZone communities deliver over 6 million pages each month to                                                             888.678.0399
more than 3.3 million software developers, architects and decision                                                       919.678.0300
makers. DZone offers something for everyone, including news,
                                                                                                                         Refcardz Feedback Welcome
                                                                                                                                                                                                             $7.95




tutorials, cheat sheets, blogs, feature articles, source code and more.
“"DZone is a developer's dream",” says PC Magazine.                                                                      refcardz@dzone.com

Copyright © 2012 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval   Sponsorship Opportunities
system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior
                                                                                                                         sales@dzone.com
                                                                                                                                                                                               Version 1.0
written permission of the publisher.

More Related Content

PDF
Neo4j - The Benefits of Graph Databases (OSCON 2009)
PPTX
Granularity in linked open data
PPTX
ACTIVITY 1-2 (VERB TO BE PAST TENSE - LISTENING EXERCISE: MICHAEL JACKSON, BL...
PDF
PPT
Tet=dsl;fjds
DOCX
Asma Mohammed Twuir Al
PDF
Datasheet EnGenius EAP300v2
PDF
Elements Essay 3101-11
Neo4j - The Benefits of Graph Databases (OSCON 2009)
Granularity in linked open data
ACTIVITY 1-2 (VERB TO BE PAST TENSE - LISTENING EXERCISE: MICHAEL JACKSON, BL...
Tet=dsl;fjds
Asma Mohammed Twuir Al
Datasheet EnGenius EAP300v2
Elements Essay 3101-11

Viewers also liked (15)

PPTX
Battery power systems
PDF
GEMC - Trauma - Cardiology and EKG Interpretation - for Medical Students
PPT
Journalistic Writing vs. "English Class" writing
PPTX
Corazon richy
PDF
Belmer portfolio overview
PPT
PDF
Presentasjon av Silver
PDF
Chiller lạnh nước giải nhiệt nước
PDF
Semantic Representations for Research
PDF
School of Business...ITM University Gwalior
PDF
3. eBook #3 Cut Labor Costs
PPT
Teaching advanced reading skills storymap 0402
PPTX
Session ii g3 overview epidemiology modeling mmc
PPT
Happy Children's Day - June 1st 2010
ODP
Haчалото на една красива приказка за агънце666666
Battery power systems
GEMC - Trauma - Cardiology and EKG Interpretation - for Medical Students
Journalistic Writing vs. "English Class" writing
Corazon richy
Belmer portfolio overview
Presentasjon av Silver
Chiller lạnh nước giải nhiệt nước
Semantic Representations for Research
School of Business...ITM University Gwalior
3. eBook #3 Cut Labor Costs
Teaching advanced reading skills storymap 0402
Session ii g3 overview epidemiology modeling mmc
Happy Children's Day - June 1st 2010
Haчалото на една красива приказка за агънце666666
Ad

Similar to Rc173 010d-json 2 (20)

PDF
Json at work overview and ecosystem-v2.0
PDF
Introduction to NoSQL and Couchbase
PDF
Json
PDF
Transition from relational to NoSQL Philly DAMA Day
PDF
Navigating the Transition from relational to NoSQL - CloudCon Expo 2012
PPT
Json
PPTX
Java and Mongo
PDF
JSON Application
PPTX
LU 1.3. JSON & XML.pptx about how they work and introduction
PDF
Development without Constraint
PDF
Json the-x-in-ajax1588
PPTX
Json
PDF
ModeShape 3 overview
PDF
Introduction to JavaScript Object Notation, Lindsay Bassett, 2015
PDF
Intro to JSON
PDF
An Introduction to JSON JavaScript Object Notation
PDF
Json demo
PDF
NoSQL for the rest of us - a JBoss perspective over those hot tools and how y...
PPTX
Realtime Analytics with MongoDB Counters (mongonyc 2012)
Json at work overview and ecosystem-v2.0
Introduction to NoSQL and Couchbase
Json
Transition from relational to NoSQL Philly DAMA Day
Navigating the Transition from relational to NoSQL - CloudCon Expo 2012
Json
Java and Mongo
JSON Application
LU 1.3. JSON & XML.pptx about how they work and introduction
Development without Constraint
Json the-x-in-ajax1588
Json
ModeShape 3 overview
Introduction to JavaScript Object Notation, Lindsay Bassett, 2015
Intro to JSON
An Introduction to JSON JavaScript Object Notation
Json demo
NoSQL for the rest of us - a JBoss perspective over those hot tools and how y...
Realtime Analytics with MongoDB Counters (mongonyc 2012)
Ad

Rc173 010d-json 2

  • 1. #127 Get More Refcardz! Visit refcardz.com Getting Started with CONTENTS INCLUDE: n Whats New in JPA 2.0 JPA 2.0 n JDBC Properties n Access Mode n Mappings n Shared Cache n Additional API and more... By Mike Keith Getting Started with JPA 2.0 DZone, Inc. | www.dzone.com
  • 2. #173 Get More Refcardz! Visit refcardz.com CONTENTS INCLUDE: ❱ JSON Validation ❱ JSON Modeling ❱ JSON in the Browser Core JSON ❱ JSON and Ajax The Fat-Free Alternative to XML ❱ JSON and Java ❱ JSON and Ruby...and More! By Tom Marrs An Object (in this case address) consists of comma-separated name/ JSON OVERVIEW value pairs surrounded by curly braces. JSON (JavaScript Object Notation) is a standard text-based data interchange format that enables applications to exchange data over a Array computer network. Programs written in Ruby, Java/EE, JavaScript, C#/. An Array is a collection of ordered values, and looks like this: Net, PHP, etc. can easily consume and produce JSON data because it is independent of languages and computing platforms. The abundance of { JSON-related APIs and tools make it easy to use JSON from your favorite “people” : [ { “firstName”: “John”, “lastName”: “Smith”, “age”: 35 }, programming language, IDE, and runtime environment. Additionlly, popular { “firstName”: “Jane”, “lastName”: “Smith”, “age”: 32 } NoSQL databases such as MongoDB and CouchBase are based on JSON. ] } JSON was created by Douglas Crockford in 2001, and is specified in RFC 4627 with the IETF (Internet Engineering Task Force) standard; see http:// tools.ietf.org/html/rfc4627. Per the specification, the JSON’s IANA (Internet Value Types Assigned Numbers Authority) media type is application/json, and the A Value (i.e., the right-hand side of a Name/Value Pair) can be one of the file type is following: .json. • Object What is JSON? • Array JSON is a simple data format, and has 3 basic data structures: • String • Name/Value (or Key/Value) Pair. • Number • Object. • Boolean • Arrays. • null A valid JSON document is always surrounded with curly braces, like this: Number A number can be an integer or double-precision float. Here are some { JSON-Data } examples: Please note that some members of the JSON community use the term “age”: 29 “string” rather than “document.” “cost”: 299.99 “temperature”: -10.5 “speed_of_light”: 1.23e11 Why JSON? “speed_of_light”: 1.23e+11 JSON is gradually replacing XML as the preferred data exchange format “speed_of_light”: 1.23E11 on the internet because JSON is easy to read and its structures map to “speed_of_light”: 1.23E+11 common programming concepts such as Objects and Arrays. JSON is more efficient (i.e., faster parsing and network transmission) than XML because JSON is more compact—there are no begin and end tags. The property name (i.e., age, etc.) is a string surrounded by double quotes, but the value does not have quotes. A number can be prefixed by a minus Name/Value Pair sign. The exponent portion (denoted by e or E) comes after the number A Name/Value pair looks like this: value, and can have an optional plus or minus sign. Neither leading zeroes, octal, nor hexadecimal values are allowed. { “firstName”: “John” } A property name (i.e., firstName) is a string that is surrounded by double quotes. A value can be a string (as in the above example), but this is just one of several valid data types. (Please see the Data Types section for further details.) Some well-known technologies claim that they use JSON data formats, but they don’t surround their strings with quotes. However, this is not valid JSON; see the JSON Validation section. Object An Object is a collection of unordered Name/Value pairs. The following example shows an address object: { Core JSON “address” : { “line1” : “555 Main Street”, “city” : “Denver”, “stateOrProvince” : “CO”, “zipOrPostalCode” : “80202”, “country” : “USA” } } DZone, Inc. | www.dzone.com
  • 3. 2 Core JSON Boolean A Boolean in JSON can either be true or false, as follows: { “emailValidated” : true } The property name (emailValid) is a string surrounded by double quotes, but the value (true) does not have quotes. null Although technically not a data type, null is a special value to indicate that a data element has no value. In the following example, the age field has no value (possibly because the user chose not to enter this information): { “age” : null } JSONLint is also available as a Chrome extension in the Chrome Web Store. Comments JSON MODELING JSON does not allow comments. Comments were originally a part of JSON, but developers misused them by putting parsing directives in comments. Developing valid JSON documents for real applications can be tedious and When Douglas Crockford saw this practice, he removed comments from error-prone. To avoid typographical errors, you can use JSONPad, JSON JSON to preserve interoperability between computing platforms. Editor Online, and JSON Designer to create a logical model (similar to UML) and generate valid JSON documents. Style You’ve probably noticed that the property names (i.e., the name on the left- JSONPad hand side of the colon) use camel case. This is not a rule or standard, but JSONPad (from http://www.jsonpad.com/en/Home.html) is a GUI tool is a convention prescribed in Google’s JSON Style Guide at: http://google- that eliminates typing JSON text by providing an interface that enables you styleguide.googlecode.com/svn/trunk/jsoncstyleguide.xml. to create Objects, Keys (i.e., Name/Value Pairs), and Arrays. JSONPad is available as a Windows or Mac GUI, and online at the JSONPad web site. Official Syntax To create a model, use the green plus key under the text area. The following Douglas Crockford’s JSON site (http://www.json.org) provides a full data types are supported: Key (i.e., Name/Value Pair), Object, and Array. description of JSON syntax. After the model is complete, press the blue up-arrow button (under the Tree tab) to generate a valid, pretty-printed JSON document based on the Additionally, the JSON Pro Quick Guide (freely available in the iPhone App model: Store) provides examples and an overview of JSON syntax. JSON VALIDATION A textual document MUST follow the JSON syntax rules to be considered a valid JSON document. Valid JSON is important because it ensures interoperability between applications and JSON-related tools. Although the JSON.org web site shows JSON syntax, sometimes it’s easier to see JSON validation in action. JSONLint (http://www.jsonlint.com) provides an interactive, web-based JSON validator. To use it, type or paste some text into the main text area and press the Validate button. If the text isn’t valid JSON, you’ll see an error message as follows: The end result is a valid JSON document that is usable in your application. You can also generate a model by pasting JSON text into the text area and pressing the green down arrow in the Tree tab. Under the Format tab, you can either compress or pretty print a JSON document. JSONPad validates the JSON document in the text are when you press the JSON button in the Tools tab. JSON Editor Online JSON Editor Online (http://jsoneditoronline.org/) is an online JSON modeler, In this case, the property name for the address Object is missing a and is also available as a Chrome extension. closing double quote. After you fix this problem and press the Validate button, JSONLint pretty-prints the JSON document as follows: JSON IN THE BROWSER Firefox and Chrome provide excellent extensions (i.e., add-ons and plugins) that make it easier to work with JSON. DZone, Inc. | www.dzone.com
  • 4. 3 Core JSON REST Client The JSONView Chrome extension provides a bit more functionality than its Rest Client is a Firefox extension that provides the ability to debug and Firefox counterpart – it enables a user to search a JSON document using test RESTful Web Services from the browser. The ability to test from the the JSONQuery language. For example, entering ..bib_key in the Query browser isn’t new, but the output formatting is much more readable. text box displays all the bib_key fields in the text: The above example uses the Books service from the Open Library API. JSONQuery is one of several technologies that can search JSON After entering the service URI, the Response Body (Highlight) tab shows the documents and return the desired element(s). JSON output. JSON Beautification with JSON SH Pretty Printing with JSONView JSON SH is a Chrome extension (available in the Google Chrome Web JSON is not very readable when displayed natively in a browser. JSONView Store) that acts as a pretty-printer and a validator. Paste a valid (but not is a Firefox and Chrome extension that pretty-prints JSON. pretty) JSON document into the text area at the top of the page, and JSON SH beautifies the text into a human-readable format. JSONView in Firefox After installing this extension and re-starting Firefox, the JSON response JSON AND AJAX from the Open Library Books service URI is readable, and you can expand/ collapse objects on the page: AJAX (Asynchronous JavaScript and XML) was one of the original use cases for JSON, and the following jQuery example shows how a JavaScript client makes an HTTP Get request to a RESTful Web Service and processes a JSON response: $.getJSON(‘http://example/service/addresses/home/1’, function(data) { var address = JSON.parse(data); console.log(“Address Line 1 = “ + address.line1); } ); In the code above, $.getJSON() (a shorthand version of the main jQuery $.ajax() call) makes an HTTP GET request. The (anonymous) success callback function receives the JSON response and parses it into a JavaScript object using JSON.parse(), which is part of the ECMA- 262 standard (beginning with the 5th edition) – please see http://www. ecmascript.org/ for further information). The console.log() method JSONView in Chrome then logs line 1 of the address to the browser console. Conversely, the JSONView is also available as a Chrome extension from the Chrome Web JSON.stringify() method converts a JavaScript value to a JSON string Store: (with optional pretty-printing). JSON AND JAVA The Jackson (http://jackson.codehaus.org/) library is a popular Java-based JSON API. Here’s an example of how to marshal/unmarshal an Address object to/from JSON: import java.io.Writer; import java.io.StringWriter; import org.codehaus.jackson.map.ObjectMapper; public class Address { private String line1; private String city; private String stateOrProvince; private String zipOrPostalCode; private String country; public Address() {} public String getLine1() { Click on the minus sign to collapse each element, and press the Toggle return line1; Collapsed link to show/hide each collapsed element. } <!---Snippet con’t on next page--> DZone, Inc. | www.dzone.com
  • 5. 4 Core JSON public void setLine1(line1) { The JSON gem’s to_json method converts a String or Hash to JSON. The this.line1 = line1; Address object’s to_json method converts an Address to JSON format } by converting its data members to a Hash and then calling to to_json on the Hash. To convert the Address to JSON, do the following: // Remaining getters and setters ... } addr1 = Address.new(‘555 Main Street’, ‘Denver’, ‘CO’, ‘80231’, Address addrOut = new Address(); ‘US’) // Call setters to populate addrOut … puts addr1.to_json ObjectMapper mapper = new ObjectMapper(); // Reuse this. # Outputs the following … {“line1”:”555 Main Street”,”city”:”Denver”,”state_or_ // Marshal Address object to JSON String. province”:”CO”,”zip_or_postal_code”:”80231”,”country”:”US”} Writer writer = new StringWriter(); mapper.writeValue(writer, addrOut); System.out.println(writer.toString()); The JSON gem’s JSON.parse method converts a JSON String to a Hash. // Unmarshal Address object from JSON String. The Address object’s from_json! method takes a JSON String, calls String addrJsonStr = JSON.parse to convert to a Hash, and sets each corresponding data “{“ + member from the Hash as follows: “”address” : {“ + “”line1” : ”555 Main Street”,” + “”city” : ”Denver”,” json_addr = <<END “”stateOrProvince” : ”CO”,” { “”zipOrPostalCode” : ”80202”,” + “line1” : “999 Broadway”, “city” : “Anytown”, “”country” : ”USA”” + “state_or_province” : “CA”, “zip_or_postal_code” : “90210”, “}” + “country” : “USA” “}”; } END Address addrIn = mapper.readValue(addrJsonStr, Address.class); addr2 = Address.new addr2.from_json!(json_addr) In addition to Jackson, other well-known Java-based JSON APIs include: In addition to the JSON gem, other JSON-related gems include: API Source Google GSON http://code.google.com/p/google-json/ API Source ActiveSupport JSON http://api.rubyonrails.org/classes/ SOJO http://sojo.sourceforge.net/ ActiveSupport/JSON.html org.json (by Douglas http://www.json.org/java Yajl https://github.com/brianmario/yajl-ruby Crockford) Oj https://github.com/ohler55/oj json-lib http://sourceforge.net/projects/json-lib/ json-io http://code.google.com/p/json-io JSON AND RUBY ON RAILS jsontools http://jsontools.berlios.de/ jsonbeans http://code.google.com/p/jsonbeans/ Ruby on Rails provides additional functionality that makes it easier to convert Ruby objects to JSON. The following controller uses the ActionController’s render method to output an Address object to JSON: JSON AND RUBY class Person There are many JSON-related libraries for Ruby. Here’s an example using attr_accessor :first_name, :last_name the JSON gem that comes standard with Ruby. def initialize(first_name=nil, last_name=nil) @first_name = first_name require ‘json’ @last_name = last_name end class Address end attr_accessor :line1, :city, :state_or_province, class MyController < ApplicationController :zip_or_postal_code, :country def index person = Person.new(‘John’, ‘Doe’) def initialize(line1=’’, city=’’, state_or_province=’’, respond_to do |format| zip_or_postal_code=’’, country=’’) format.html # index.html.erb @line1 = line1 format.json { render :json => person} @city = city end @state_or_province = state_or_province end @zip_or_postal_code = zip_or_postal_code end @country = country end The Rails ApplicationController takes care of marshalling/ def to_json unmarshalling objects to/from JSON, so there’s no need to write a to_ to_hash.to_json end json method here. def from_json!(str) JSON.parse(str).each { |var, val| send(“#{var}=”, val) } JSON SCHEMA end private JSON Schema specifies the structure of a JSON document. JSON Schema can be used to validate the content of JSON sent to/received from a def to_hash RESTful Web Service. JSON Schemas are written in JSON. Hash[instance_variables.map { |var| [var[1..-1].to_sym, send(var[1..-1])] }] The main JSON Schema site can be found at: http://json-schema.org. end JSON Schema is a work in progress – the JSON Schema team has just end published version 0.4, which can be found at: http://tools.ietf.org/html/ draft-zyp-json-schema-04. Some important JSON Schema constructs include: DZone, Inc. | www.dzone.com
  • 6. 5 Core JSON Construct Description “phoneNumber”: { “type”: “object”, type The data type object, array, string, number, etc. “id”: “phoneNumber”, “required”: true, $schema The URI that provides the schema version. “properties”: { required true/false “channel”: { “type”: “string”, id Data element id “id”: “channel”, “required”: true, properties Validation properties for a data element include type (see “enum”: [ above), minimum (minimum value), maximum (maximum “cell”, “work”, value), enum, etc. “home” ] Here is a sample JSON Schema for a portion of an online gift registry: }, “number”: { “type”: “object”, “type”: “string”, “$schema”: “http://json-schema.org/draft-03/schema”, “id”: “number”, “id”: “#”, “required”: true “required”: true, } “properties”: { } “registrants”: { } “type”: “array”, } “id”: “registrants”, } “required”: true, } “items”: { } “type”: “object”, } “required”: false, “properties”: { “address”: { The above schema: “type”: “object”, “id”: “address”, “required”: true, • Requires an array of registrant objects. “properties”: { • Limits the phoneNumber.channel field to the following values: “city”: { cell, work, fax, or home. “type”: “string”, • Limits the address.premise field to these values: home, work, or “id”: “city”, “required”: true other. }, “country”: { A Web Service consumer could use this schema to validate the following “type”: “string”, JSON document: “id”: “country”, “required”: false }, { “line1”: { “registrants”: [ “type”: “string”, { “id”: “line1”, “firstName”: “Fred”, “required”: true “lastName”: “Smith”, }, “phoneNumber”: { “line2”: { “channel”: “cell”, “type”: “string”, “number”: “303-555-1212” “id”: “line2”, }, “required”: false “address”: { }, “premise”: “home”, “postalCode”: { “line1”: “555 Broadway NW”, “type”: “string”, “line2”: “# 000”, “id”: “postalCode”, “city”: “Denver”, “required”: true “stateOrProvince”: “CO”, }, “postalCode”: “88888”, “premise”: { “country”: “USA” “type”: “string”, } “id”: “premise”, } “required”: true, ] “enum”: [ } “work”, “home”, “other” ] }, JSON Schema Generator “stateOrProvince”: { Creating a JSON Schema is tedious and error-prone. Use a JSON Schema “type”: “string”, Generator to generate a Schema from any valid JSON document. Visit the “id”: “stateOrProvince”, online JSON Schema Generator (www.jsonschema.net/) and generate a “required”: true } schema by doing the following: } }, • Paste the JSON document into the right-hand text area. “firstName”: { • Choose the JSON Input option “type”: “string”, “id”: “firstName”, • Press the Generate Schema button. “required”: true }, “lastName”: { JSON Schema Validator “type”: “string”, An application uses a JSON Schema Validator to ensure that a JSON “id”: “lastName”, document conforms to the structure specified by the Schema. JSON “required”: true Schema Validators are available for most modern programming languages: }, JSON Schema Language Source Validator JSV JavaScript https://github.com/garycourt/JSV Ruby JSON Schema Ruby https://github.com/hoxworth/json- <!============Snippet con’t on next page------------------> Validator schema DZone, Inc. | www.dzone.com
  • 7. 6 Core JSON JSON Schema Language Source Validator json-schema- Java https://github.com/fge/json- validator schema-validator php-json-schema PHP https://github.com/hasbridge/php- (by MIT) json-schema JSON.Net .NET http://james.newtonking.com/ projects/json-net.aspx Besides the language-specific tools, there is an excellent online JSON Schema Validator at: http://json-schema-validator.herokuapp.com. To use this site, enter the JSON document and Schema into the corresponding text boxes and press the Validate button. IN CONCLUSION We’ve covered the basics of JSON, but we’ve just scratched the surface. Although JSON is a simple data format, there are many tools to streamline the design and development process. JSON is a standard, it has replaced XML as the preferred data interchange format on the Internet, and it enables developers to create efficient, interoperable enterprise-class applications. ABOUT THE AUTHORS RECOMMENDED BOOK Tom Marrs is a Principal Architect at Ciber, where he With JavaScript: The Good Parts, you’ll discover a specializes in Service-Oriented Architecture (SOA) He beautiful, elegant, lightweight and highly expressive designs and implements mission-critical web and language that lets you create effective code, whether business applications using the latest SOA, Ruby on you’re managing object libraries or just trying to get Rails, REST, HTML5, JavaScript, Java/EE, and Open Ajax to run fast. If you develop sites or applications for Source technologies. Tom is also the author of the the Web, this book is an absolute must. upcoming JSON at Work, and a founder of the Denver Open Source User Group (DOSUG) Buy Here. Browse our collection of over 150 Free Cheat Sheets Upcoming Refcardz Free PDF Debugging Patterns Clean Code Cypher Object-Oriented JS DZone, Inc. 150 Preston Executive Dr. Suite 201 Cary, NC 27513 DZone communities deliver over 6 million pages each month to 888.678.0399 more than 3.3 million software developers, architects and decision 919.678.0300 makers. DZone offers something for everyone, including news, Refcardz Feedback Welcome $7.95 tutorials, cheat sheets, blogs, feature articles, source code and more. “"DZone is a developer's dream",” says PC Magazine. refcardz@dzone.com Copyright © 2012 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval Sponsorship Opportunities system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior sales@dzone.com Version 1.0 written permission of the publisher.