Handling JSON in Apex Shamil Arsunukayev Technical Architect, Comity Designs

Slides:



Advertisements
Similar presentations
Control Flow Statements: Repetition/Looping
Advertisements

Programming Languages and Paradigms The C Programming Language.
Advanced Indexing Techniques with Apache Lucene - Payloads Advanced Indexing Techniques with Michael Busch
Advanced Indexing Techniques with
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 24 - VBScript Outline 24.1 Introduction 24.2 Operators 24.3 Data Types and Control Structures.
Lecture # 21 Chapter 6 Uptill 6.4. Type System A type system is a collection of rules for assigning type expressions to the various parts of the program.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
General Computer Science for Engineers CISC 106 Lecture 33 Dr. John Cavazos Computer and Information Sciences 05/11/2009.
JavaScript, Third Edition
Connect with life Vinod Kumar M Technology Evangelist | Microsoft
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
Sage CRM Developers Course Programming for the Advanced Manager.
SCRAPING BUSINESS ADDRESSES Anisha S. Agenda When business URLs are present When business URLs are not present; What is present is a list of keywords.
Forms and Java script. Forms The graphical user interface -textbox, radio, button, textarea, checkbox… The processing script –CGI scripts, Perl script,
Doing Something Useful with Enterprise Library 3.0 Benjamin Day Level: Intermediate.
Partners’ Webinar 10/25/2012 Karol Jarkovsky Solution Architect E-commerce Scenarios.
@CRMUG Technical Academy Fetch Xml Were can Fetch Xml be used Basic Fetch Xml and using advanced find to build your own Fetch Query Creating Fetch Xml.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
T.E.A.M. Training: Microsoft Outlook 2010 Scheduling & Facilitating Meetings.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
Introduction to Programming (in JavaScript) in 10 minutes …hopefully Else.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Types in programming languages1 What are types, and why do we need them?
Using Ajax to Improve uPortal User Experience Jen Bourey Yale University
1 © 2000 John Urrutia. All rights reserved. Session 5 The Bourne Shell.
Chapter 3 Object Interaction.  To construct interesting applications it is not enough to build individual objects  Objects must be combined so they.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
IBM TSpaces Lab 2 Customizing tuples and fields. Summary Blocking commands Tuple Expiration Extending Tuples (The SubclassableTuple) Reading/writing user.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
CS 153: Concepts of Compiler Design September 30 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Developed at Sun Microsystems in 1991 James Gosling, initially named “OAK” Formally announced java in 1995 Object oriented and cant write procedural.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Chapter 1 Introduction to PHP Part 1. Textbook’s Code DOWNLOADS PHP and MySQL for Dynamic Web Sites Complete Set of Scripts.
6 Copyright © 2004, Oracle. All rights reserved. Adding Custom Validation.
Control Flow Statements
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
PYTHON PROGRAMMING Week 3 - Tuesday. STARTER Hour of Code Video.
Data Mangling The key to data-management within your Flex Applications.
SHAREPOINT SATURDAY PRESENTATION by Keith Rimington REAL EXPERIENCES WITH ANGULARJS AND SHAREPOINT.
COMM 3050 – Online Project Update. Project Roles  Organizer Responsible for creating Zoom account technical aspects and posting recorded meeting to S:
Hybris Payment Integration
LESSON 5 LOOPING AND BRANCHING Azalya Rahmatika Fathul Fithrah JURUSAN MATEMATIKA FAKULTAS MATEMATIKA DAN ILMU PENGETAHUAN ALAM UNIVERSITAS SYIAH KUALA.
Object Oriented Programming Lecture 2: BallWorld.
Client-side (JavaScript) Validation. Associating a function with a click event – Part 1 Use the input tag’s onclick attribute to associate a function.
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Introduction to PHP Part 1
The Boolean Boost: Searching for Candidates
SQL Server 2016 JSON Support FOR Data Warehousing
Expressions and Control Flow in JavaScript
Java Programming: Guided Learning with Early Objects
Website: Contact No: ID:
Google API Key.
Exception Handling: A Deeper Look
null, true, and false are also reserved.
Chapter 9 Web Services: JAX-RPC, WSDL, XML Schema, and SOAP
M-RETS Subscriber & Regulator Group Meeting
Selection CSCE 121 J. Michael Moore.
Event Sponsors Expo Sponsors Expo Light Sponsors.
University of Kurdistan
A Telephone Contact A brief statement that describes who you are,
PROGRAM FLOWCHART Selection Statements.
C# Revision Cards Data types
Problem 1 Given n, calculate 2n
Article Title: Source: Date:
True or False True or False
Presentation transcript:

Handling JSON in Apex Shamil Arsunukayev Technical Architect, Comity Designs

Agenda  System.JSON  System.JSONGenerator  System.JSONParser  Demo: Google Calendar APIs + JSON + Apex  Q&A

System.JSON JSON.serialize: Account acctOne = [SELECT id, name FROM Account LIMIT 1]; String acctJSON = JSON.serialize(acctOne); JSON.deserialize: Account acctTwo = (Account) JSON.deserialize(acctJSON, Account.class);  Minimum number of script statements  No need to use Dynamic Apex to inspect the metadata, it’s all automatic!

CalendarList Resource JSON { "kind": "calendar#calendarListEntry", "etag": etag, "id": string, "summary": string, "hidden": boolean, … "defaultReminders": [ { "method": string, "minutes": integer } ] }

GoogleCalendar Apex Class public class GoogleCalendar { public String id; public String kind; public String etag; public String summary; public Boolean hidden; … public List defaultReminders; }

System.JSON public String serialize() { return JSON.serialize(this); } public void deserialize(String jsonString) { GoogleCalendar gCal = (GoogleCalendar) JSON.deserialize(jsonString, GoogleCalendar.class); … }  Notice how Apex objects are used instead of sObjects

System.JSON Note: If GoogleCalendar Apex class didn’t have a field or fields to match the CalendarList JSON structure, the JSON.deserialize() method would have failed with the “System.JSONException: Unknown field field_name “ exception

JSONGenerator  Contains methods used to serialize Apex objects into JSON content using the standard JSON encoding.  Useful for wrapping or aggregating values  Can be used instead of the JSON.serialize() if the latter could not be used List contacts = [Select Id, Name From Contact]; generator.writeStartObject(); generator.writeNumberField(‘count’, contacts.size()); generator.writeEndObject(); String jsonString = generator.getAsString();

Event Resource JSON { “summary": string, “end": { < ‘end’ is a reserved Apex keyword "date": date, < ‘date’ is a reserved Apex keyword … }, "attendees": [ { " ": string, … } ], "reminders": { "useDefault": boolean, "overrides": [ { "method": string, "minutes": integer } ] }

GoogleCalendarEvent Apex Class public class GoogleCalendarEvent { public String summary; … public GoogleEventTime start; public GoogleEventTime gEnd; //renamed ‘end’ public List attendees; public GoogleReminder reminders; }

JSONGenerator JSONGenerator gen = JSON.createGenerator(true); gen.writeStartObject(); gen.writeStringField('summary', ‘New event’); gen.writeFieldName('start'); gen.writeStartObject(); gen.writeObjectField('dateTime', System.now().addDays(1)); //or gen. writeDateTimeField('dateTime', System.now().addDays(1)); gen.writeEndObject(); { “summary”: “New event", "start": { "dateTime": " T18:03:32-08:00“ }, …

JSONGenerator gen.writeFieldName('reminders'); gen.writeObject(reminders); //reminders is a GoogleReminder object … "reminders": { "useDefault": false, "overrides": [ { "method": " ", "minutes": 1 }, { "method": " ", "minutes": 2 } ] }…

GoogleReminder Apex Class public class GoogleReminder { public Boolean useDefault; public List overrides; } public class GoogleReminderOverride { public String method; public Integer minutes; }

JSONGenerator gen.writeFieldName('attendees'); gen.writeStartArray(); for(GoogleEventAttendee gEventAttendee: this.attendees){ gen.writeStartObject(); gen.writeStringField(' ', gEventAttendee. ); gen.writeBooleanField('optional', gEventAttendee.optional); gen.writeNumberField('additionalGuests', gEventAttendee.additionalGuests); gen.writeEndObject(); } gen.writeEndArray(); … String jsonString = gen.getAsString(); //create a JSON string

JSONGenerator "attendees": [ { " ": "optional": false, "additionalGuests": 1 }, { " ": "optional": true, "additionalGuests": 2 },... ]

JSONParser  Generally, JSONParser is useful for grabbing specific pieces of data without the need for a structure such as an Apex class JSONParser parser = JSON.createParser(resp); while (parser.nextToken() != null) { if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)){ String fieldName = parser.getText(); parser.nextToken(); if(fieldName == 'access_token') { accesstoken = parser.getText(); } else if(fieldName == 'expires_in'){ expiresIn = parser.getIntegerValue(); } }}

JSONParser "attendees": [ { " ": "optional": false, "additionalGuests": 1 }, { " ": "optional": true, "additionalGuests": 2 },... ]

JSONParser … if(fieldName == 'attendees'){ if(parser.getCurrentToken() == JSONToken.START_ARRAY){ while(parser.nextToken() != null){ if(parser.getCurrentToken() == JSONToken.START_OBJECT){ GoogleEventAttendee gEventAttendee = (GoogleEventAttendee) parser.readValueAs(GoogleEventAttendee.class); this.attendees.add(gEventAttendee); } else if(parser.getCurrentToken() == JSONToken.END_ARRAY){ break; }}}}

Demo: Google Calendar APIs + JSON + Apex

Thank you Questions & Answers