2. Agenda
•
•
•
•
•
•
•
What is JSON
Advantage of JSON over XML
Other reasons to use JSON
JSON Syntax / Guidelines
Deserialize and Serialize in Single line - Winter 12
Visualforce Page Output as JSON
Google Map API - Demo
1
3. What is JSON
•
•
•
•
•
JSON Stands for “JavaScript Object Notation”.
Language Independent representation of objects.
Parsers widely available in many languages.
Alternative to XML.
JSON can be transmitted over http / https.
2
6. JSON Advantage over XML
• XML is Verbose.
• More size than of equivalent JSON representation
because of repeated Tags.
• JSON Simple to represent
5
7. Why JSON
• REST is very common and supports JSON widely.
• REST and JSON are the music of the internet.
• Google , Yahoo, D&B web services exposed as REST
with response type JSON.
6
8. JSON Guidelines
Key – Value enclosed in double quotes (String).
Value - can again anything of datatype.
{} – represents Object
[] – represents Array
, - Separates data element within Object
Supports basically four data type:
1. Boolean
2. Number
3. String
4. Object
7
10. How to Work with JSON – Before
Winter 12
• AppExchange and other codes were available for
Parsing JSON.
• Performance Overhead.
• Learning curve more.
9
11. Deserialize JSON – Winter 12 API
JSON String :
{
“FirstName” : “Foo”,
“LastName” : “Bar”
}
Equivalent Apex Class:
Class Person
{
public String FirstName;
public String LastName;
}
10
12. Deserialize JSON – Single Line
Person d = (Person )System.JSON.deserialize(jsonString, Person.class);
JSON Format String
Determine the output
object type of the JSON
11
13. Serialize Apex Class to JSON
JSON.serialize(object);
Object to convert to
JSON
12
16. Demo
Get distance between two points using Google API
http://maps.googleapis.com/maps/api/distancematrix/json?origi
ns=Nagpur+Maharashtra+india&destinations=Pune+Maharasht
ra+india&sensor=false
15
18. Apex Class Equivalent to JSON
response
Class GoogleResponse
{
public String[] destination_addresses;
public String[] origin_addresses;
public Row[] rows;
public String status;
}
Class Row
{
public Elements[] elements;
}
Class Elements
{
public
public
public
}
Class Values
{
public
public
}
17
Values distance;
Values duration;
String status;
String text;
String value;