SlideShare una empresa de Scribd logo
1 de 32
Descargar para leer sin conexión
© 2010 Marty Hall
Automatically
Generating JSON from
Java ObjectsJava Objects
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/ajax.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
http://courses.coreservlets.com/Course Materials/ajax.html
© 2010 Marty Hall
For live Ajax & GWT training, see training
t htt // l t /courses at http://courses.coreservlets.com/.
Taught by the author of Core Servlets and JSP,
More Servlets and JSP and this tutorial Available atMore Servlets and JSP, and this tutorial. Available at
public venues, or customized versions can be held
on-site at your organization.
C d l d d t ht b M t H ll
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
• Courses developed and taught by Marty Hall
– Java 6, servlets/JSP (intermediate and advanced), Struts, JSF 1.x, JSF 2.0, Ajax, GWT 2.0 (with GXT), custom mix of topics
– Ajax courses can concentrate on 1 library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, Google Closure) or survey several
• Courses developed and taught by coreservlets.com experts (edited by Marty)
– Spring, Hibernate/JPA, EJB3, Web Services, Ruby/Rails
Contact hall@coreservlets.com for details
Topics in This Section
• Using org.json Java utilities
– Building JSON object from bean
– Building JSON array from Java array or List
Building JSON object from Map– Building JSON object from Map
– Other JSON-generation utilities
• Using json2.js JavaScript utilitiesUsing json2.js JavaScript utilities
– Sending JSON objects to server
4
© 2010 Marty Hall
Intro and Setup
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Using MVC to Build JSON
• Last section: used MVC to build JSON
– Advantages
• Requires no special server software
• You have full control over resultYou have full control over result
– Disadvantages
• Tedious for complex data structures
Oft i k l d f h ill d t• Often requires knowledge of how server will use data
• This section: turning Java into JSON
– AdvantagesAdvantages
• Can generate complex data easily
• Builds real objects so server can decide what to do
Di d– Disadvantages
• Requires JSON-specific server software
• Sometimes builds objects with unneeded data in them6
Installing the org.json.* Utilities
• Download
– http://www.json.org/java/json.zip
• Or start at http://www.json.org/java/ and follow link that
says “Free source code is available”.y
• Install
– Unzip to get org/json/*.java
– Put into src folder of Eclipse
• Create new package org.json, then copy files there
– They do not supply a JAR file but you could easily build– They do not supply a JAR file, but you could easily build
one yourself, then put JAR file in WEB-INF/lib
• Built org.json-utils.jar and put online at coreservlets.com
• Documentation
– http://www.json.org/java/
7
Configuring Eclipse Project
Used only in last example. Available for download at
http://www.json.org/json2.js. You can also get compressed
version; see http://www.json.org/js.html.version; see http://www.json.org/js.html.
Used in all examples. Available for download at
http://courses coreservlets com/Course-Materials/ajax html
8
http://courses.coreservlets.com/Course-Materials/ajax.html
Downloaded latest .java files from http://www.json.org/java/,
compiled, and put resultant .class files in JAR file. Or, you can put
.java files from http://www.json.org/java/ directly in src/org.json.
Other JSON-Generation
SoftwareSoftware
• org.json utilities (used in this tutorial)
Wid l d– Widely used
• Used within other utilities (e.g., JSON-RPC)
– Limited power
Alt ti• Alternatives
– Google Gson
• Better support for generics
htt // d l / / l /• http://code.google.com/p/google-gson/
– JSON Taglib
• More usable directly from JSP
http://json taglib sourceforge net/• http://json-taglib.sourceforge.net/
– VRaptor
• Uses annotations for much of the work
• http://vraptor org/ajax html• http://vraptor.org/ajax.html
– Many more
• See “Java” entry at http://json.org/
9
© 2010 Marty Hall
Supporting Java CodeSupporting Java Code
(Used in All Examples)
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Main Bean: City.java
• Constructor
public City(String name, int timeZone, int pop) {
setName(name);
setTimeZone(timeZone);
setPop(pop);setPop(pop);
}
• Getter methods
– getName
– getTime, getTimeZone
• Assumes server is in US east coasts subtracts 0-3 hoursAssumes server is in US east coasts, subtracts 0 3 hours
based on time zone
– getPop
Raw population as an int• Raw population as an int
– getPopulation
• Formatted population as a String with commas11
Utilities for Finding Beans:
CityUtils javaCityUtils.java
• Map that associates city name with City
private static Map<String,City> biggestAmericanCities =
new HashMap<String,City>();
• Populate it with largest US cities
L k f ti• Lookup functions
public static City getCity(String name) {
name = name.toUpperCase();
return(biggestAmericanCities.get(name));
}
12
Utilities for Finding Beans:
CityUtils java ContinuedCityUtils.java Continued
• Map that associates category of cities with
icity names
private static Map<String,String[]> cityTypeMap;
• Lookup function
public static List<City> findCities(String cityType) {
String[] cityNames = cityTypeMap get(cityType);String[] cityNames cityTypeMap.get(cityType);
if (cityNames == null) {
String[] twoCities = { "New York", "Los Angeles" };
cityNames = twoCities;
}
List<City> cities = new ArrayList<City>();
for(String cityName: cityNames) {
cities add(getCity(cityName));cities.add(getCity(cityName));
}
return(cities);
}13
Parent Servlet Class:
ShowCities javaShowCities.java
public abstract class ShowCities extends HttpServlet {
public void doGet(HttpServletRequest request,public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setContentType("text/javascript");
List<City> cities = getCities(request);
outputCities(cities, request, response);
}
protected List<City> getCities(HttpServletRequest request) {protected List<City> getCities(HttpServletRequest request) {
String cityType = request.getParameter("cityType");
return(CityUtils.findCities(cityType));
}}
14
Parent Servlet Class:
ShowCities java ContinuedShowCities.java Continued
public void doPost(HttpServletRequest request,
HttpServletResponse response)HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public abstract void outputCities
(List<City> cities,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException;
}}
15
© 2010 Marty Hall
General Approach
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Steps for Servlet Using JSON
UtilitiesUtilities
• Set normal response headers
tH d f P d C h C t l– response.setHeader for Pragma and Cache-Control
• Set Content-Type to text/javascript
– response.setContentType("text/javascript");
• Get PrintWriter in normal manner
– PrintWriter out = response.getWriter
• Get result as bean array or Map• Get result as bean, array, or Map
– Call normal business logic code
• Turn Java object into JSONObject
– JSONObject result = new JSONObject(bean);
– JSONArray result = new JSONArray(arrayOfBeans, false);
– JSONObject result = new JSONObject(map);j j ( p)
• Output JSONObject with print
– out.print(result);
17
Steps for Using JSON Utilities:
Sample Servlet CodeSample Servlet Code
public void doPost(HttpServletRequest request,
HttpServletResponse response)HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setContentType("text/javascript");
PrintWriter out = response.getWriter();
SomeBean javaResult = callSomeBusinessLogic(…);
JSONObject jsonResult = new JSONObject(javaResult);
out.print(jsonResult);p (j );
}
These two lines are the only ones that typically change
f li ti t li ti Oth li t tl i
18
from application to application. Other lines stay exactly as is.
© 2010 Marty Hall
Turning Java BeansTurning Java Beans
into JSONObjectj
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Turning Beans into JSON
• org.json defines JSONObject
I S i h d b ild JSON f– Its toString method builds JSON format
• Most important constructor takes a bean
– JSONObject json = new JSONObject(myBean);JSONObject json new JSONObject(myBean);
• Second arg of “true” means to include superclass info
– Result
• Uses reflection on myBean to find all public methods of the• Uses reflection on myBean to find all public methods of the
form getBlah (any return type) or isBlah (boolean return)
• Calls each getter method
• If myBean has getFoo and getBar, it builds object of theIf myBean has getFoo and getBar, it builds object of the
form { "foo": "getFoo() result", "bar": "getBar() result"}
• Other capabilities
Can turn Map into JSONObject (keys become properties)– Can turn Map into JSONObject (keys become properties)
– Can add properties one at a time with “put”
20
JSONObject from Bean:
Example CodeExample Code
package coreservlets;
import org.json.*;
public class CityTest1 {public class CityTest1 {
public static void main(String[] args) {
City sf = CityUtils.getCity("San Francisco");
JSONObj t fJSON JSONObj t( f)JSONObject sfJSON = new JSONObject(sf);
System.out.println("JSON version of SF is:n" +
sfJSON);
}
}
21
Note: toString is automatically called when you print an
Object in Java. It is the toString method of JSONObject that
builds the JSON representation.
JSONObject from Bean:
Example ResultExample Result
JSON version of SF is:
{"time": "06:00:55 AM"{"time": "06:00:55 AM",
"name": "San Francisco",
"timeZone": -3,
"pop": 744041,
"population": " 744,041"}
• (White space added for readability)
22
Building Arrays of JSON Info
• org.json defines JSONArray
– Its toString method outputs array in JSON format
• Most important constructors
JSONA (j A O C ll i )– new JSONArray(javaArrayOrCollection)
• Assumes javaArrayOrCollection contains primitives,
Strings, or JSONObjects
– new JSONArray(javaArrayOrCollection, false)
• Assumes javaArrayOrCollection contains beans that
should be converted as in previous section, but you don’tp , y
want to include superclass info
– new JSONArray(javaArrayOrCollection, true)
• Assumes javaArrayOrCollection contains beans that• Assumes javaArrayOrCollection contains beans that
should be converted as in previous section, but you do
want to include superclass info
23
JSONArray: Example Code
package coreservlets;
import org.json.*;
import java.util.*;
public class CityTest2 {
public static void main(String[] args) {
List<City> biggestUSCities =List<City> biggestUSCities
CityUtils.findCities("top-5-cities");
JSONArray citiesJSON =
new JSONArray(biggestUSCities, false);e JSO ay(b ggestUSC t es, a se);
System.out.println("JSON version of biggest " +
"US cities is:n" +
citiesJSON););
}
}
24
JSONArray: Example Result
JSON version of biggest US cities is:
[{"time":"09:14:16 AM" "name":"New York"[{"time":"09:14:16 AM", "name":"New York",
"timeZone":0,"pop":8250567,"population":"8,250,567"},
{"time":"06:14:16 AM", "name":"Los Angeles",
"timeZone": 3 "pop":3849368 "population":"3 849 368"}"timeZone":-3,"pop":3849368,"population":"3,849,368"},
{"time":"08:14:16 AM", "name":"Chicago",
"timeZone":-1,"pop":2873326,"population":"2,873,326"},
{"ti " "08 14 16 AM" " " "H t "{"time":"08:14:16 AM", "name":"Houston",
"timeZone":-1,"pop":2144491,"population":"2,144,491"},
{"time":"07:14:16 AM", "name":"Phoenix",
"ti Z " 2 " " 1512986 " l ti " "1 512 986"}]"timeZone":-2,"pop":1512986,"population":"1,512,986"}]
• (White space added for readability)(White space added for readability)
25
© 2010 Marty Hall
C i M l dComparing Manual and
Automatic JSON Generation
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.26
Manual Generation: Server Code
(Servlet)(Servlet)
public class ShowCities1 extends ShowCities {
public void outputCities(List<City> citiespublic void outputCities(List<City> cities,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException IOException {throws ServletException, IOException {
request.setAttribute("cities", cities);
String outputPage =
"/WEB INF/ lt / iti j j ""/WEB-INF/results/cities-json.jsp";
RequestDispatcher dispatcher =
request.getRequestDispatcher(outputPage);
di t h i l d ( t )dispatcher.include(request, response);
}
}
27
Manual Generation: Server Code
(JSP)(JSP)
{ headings: ["City", "Time", "Population"],
cities: [["${cities[0] name}" "${cities[0] time}"cities: [["${cities[0].name}", "${cities[0].time}",
"${cities[0].population}"],
["${cities[1].name}", "${cities[1].time}",
"${cities[1].population}"],
["${cities[2].name}", "${cities[2].time}",
"${cities[2].population}"],
["${cities[3].name}", "${cities[3].time}",
"${cities[3].population}"],
["${cities[4].name}", "${cities[4].time}",[ ${ [ ] } , ${ [ ] } ,
"${cities[4].population}"]]
}
28
Manual Generation: Client Code
function cityTable1(address, inputField, resultRegion) {
var data = "cityType=" + getValue(inputField);var data = "cityType=" + getValue(inputField);
ajaxPost(address, data,
function(request) {
showCityInfo1(request resultRegion);showCityInfo1(request, resultRegion);
});
}
• Note:
– ajaxPost shown in previous tutorial sectionajaxPost shown in previous tutorial section
• Sends data via POST and passes result to handler
function
29
Manual Generation: Client Code
(Continued)(Continued)
// Data that arrives is JSON object with two properties:
// headings (an array of strings for the th elements)// - headings (an array of strings for the th elements)
// - cities (an array of array of strings
// matching the heading names)
function showCityInfo1(request, resultRegion) {
if ((request.readyState == 4) &&
( t t t 200)) {(request.status == 200)) {
var rawData = request.responseText;
var data = eval("(" + rawData + ")");
t bl tT bl (d t h di d t iti )var table = getTable(data.headings, data.cities);
htmlInsert(resultRegion, table);
}
}
30
Manual Generation: HTML Code
<fieldset>
<legend>JSON Data: Original MVC Approach</legend>g g pp / g
<form action="#">
<label for="city-type-1">City Type:</label>
<select id="city-type-1">
/<option value="top-5-cities">Largest Five US Cities</option>
<option value="second-5-cities">Second Five US Cities</option>
…
</select>/se ect
<br/>
<input type="button" value="Show Cities"
onclick='cityTable1("show-cities-1", "city-type-1",
/"json-city-table-1")'/>
</form>
<p/>
<div id="json-city-table-1"></div><div id json city table 1 ></div>
</fieldset>
31
Manual Generation: Results
32
Manual Generation:
Pros and ConsPros and Cons
• Advantages
– Requires no JSON-specific software on server
– Java code is moderately simple
Client code is simple– Client code is simple
• Disadvantages
– JSP code is complexJSP code is complex
– JSP code cannot adapt to arbitrary number of cities
• This can be fixed with JSTL – see next tutorial section
– Server code needs to know a lot about how client code
will use results. Server code essentially pre-processed the
data and put it in form ready for presentation.p y p
• If you are going to do that, why bother with data-centric
Ajax? Why not just send HTML table from the server?
33
Automatic Generation: Server
Code (Servlet)Code (Servlet)
public class ShowCities2 extends ShowCities {
public void outputCities(List<City> citiespublic void outputCities(List<City> cities,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException IOException {throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(new JSONArray(cities, false));
}}
}
34
Automatic Generation: Server
Code (JSP)Code (JSP)
• None!
35
Automatic Generation: Client
CodeCode
function cityTable2(address, inputField, resultRegion) {
var data = "cityType=" + getValue(inputField);var data = "cityType=" + getValue(inputField);
ajaxPost(address, data,
function(request) {
showCityInfo2(request resultRegion);showCityInfo2(request, resultRegion);
});
}
• Note:
– Only difference from previous example is that result isOnly difference from previous example is that result is
passed to showCityInfo2 instead of ShowCityInfo1
36
Automatic Generation: Client
Code (Continued)Code (Continued)
// Data that arrives is an array of city objects.
// City objects contain (among other things)// City objects contain (among other things)
// name, time, and population properties.
function showCityInfo2(request, resultRegion) {
if ((request.readyState == 4) &&
(request.status == 200)) {
var rawData = request.responseText;
var cities = eval("(" + rawData + ")");var cities = eval( ( + rawData + ) );
var headings = ["City", "Time", "Population"];
var rows = new Array();
for(var i=0; i<cities.length; i++) {
var city = cities[i];
rows[i] = [city.name, city.time, city.population];
}
t bl tT bl (h di )var table = getTable(headings, rows);
htmlInsert(resultRegion, table);
}
}37
Automatic Generation:
HTML CodeHTML Code
<fieldset>
<legend>JSON Data: Automatic Conversion of Lists</legend>g / g
<form action="#">
<label for="city-type-2">City Type:</label>
<select id="city-type-2">
/<option value="top-5-cities">Largest Five US Cities</option>
<option value="second-5-cities">Second Five US Cities</option>
…
</select>/se ect
<br/>
<input type="button" value="Show Cities"
onclick='cityTable2("show-cities-2", "city-type-2",
/"json-city-table-2")'/>
</form>
<p/>
<div id="json-city-table-2"></div><div id json city table 2 ></div>
</fieldset>
38
Automatic Generation: Results
39
Automatic Generation:
Pros and ConsPros and Cons
• Advantages
J d i i l– Java code is very simple
– No JSP whatsoever
– Server code can adapt to arbitrary number of citiesp y
– Server code does not need to know how client code will
use the result
– Client code has “real” data so can do logic based on itClient code has real data so can do logic based on it
• Disadvantages
– Requires JSON-specific software on server
– Client code is more complex
• It needs to extract data from objects before sending it to
table-building function
– Extra fields were sent
• Client did not use timeZone and pop properties, but they
were sent anyway40
© 2010 Marty Hall
Turning Java MapsTurning Java Maps
into JSONObjectj
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Building JSONObject from Map
• Most important JSONObject constructors
– new JSONObject(bean)
• Uses reflection on myBean to find all public methods of the
form getBlah (any return type) or isBlah (boolean return)g ( y yp ) ( )
• Calls each getter method
• If myBean has getFoo and getBar, it builds object of the
form { "foo": "getFoo() result", "bar": "getBar() result"}form { foo : getFoo() result , bar : getBar() result }
– new JSONObject(bean, true)
• Same as above but includes inherited methods
Oth t t• Other constructors
– new JSONObject(map)
• Map keys become JSON property namesMap keys become JSON property names
– new JSONObject(string)
• Useful when passing JSON to the server42
JSONObject from Map:
Example CodeExample Code
package coreservlets;
import org.json.*;
import java.util.*;
public class CityTest3 {
public static void main(String[] args) {
M <St i St i []> itiMap<String,String[]> cities =
CityUtils.getCityTypeMap();
JSONObject citiesJSON =
( )new JSONObject(cities);
System.out.println("JSON version of map of " +
"US cities is:n" +
citiesJSON);
}
}43
JSONObject from Map:
Example ResultExample Result
JSON version of map of US cities is:
{"superbowl-hosts":{ superbowl hosts :
["Phoenix","Miami",
"Detroit","Jacksonville","Houston"],
"top-5-cities":top 5 cities :
["New York","Los Angeles",
"Chicago","Houston","Phoenix"],
"cities-starting-with-s":cities starting with s :
["San Antonio","San Diego",
"San Jose","San Francisco","Seattle"],
"second-5-cities":seco d 5 c t es :
["Philadelphia","San Antonio",
"San Diego","Dallas","San Jose"]}
• (White space added for readability)
44
Converting Maps: Server Code
public class ShowCityTypes extends HttpServlet {
public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response setHeader("Cache-Control" "no-cache");response.setHeader( Cache Control , no cache );
response.setHeader("Pragma", "no-cache");
response.setContentType("text/javascript");
PrintWriter out = response.getWriter();PrintWriter out response.getWriter();
JSONObject cityTypes =
new JSONObject(CityUtils.getCityTypeMap());
out.println(cityTypes);out.p t (c ty ypes);
}
45
Converting Maps: Server Code
(Continued)(Continued)
public void doPost(HttpServletRequest requestpublic void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request response);doGet(request, response);
}
}
46
Converting Maps: Client Code
function cityTypeList(address, resultRegion) {
ajaxPost(address nullajaxPost(address, null,
function(request) {
showCityTypeInfo(request, resultRegion);
});});
}
// Data that arrives is an object where the
// properties are city categories and the
// associated values are arrays of city names.// assoc ated a ues a e a ays o c ty a es.
47
Converting Maps: Client Code
(Continued)(Continued)
function showCityTypeInfo(request, resultRegion) {
if ((request.readyState == 4) &&if ((request.readyState 4) &&
(request.status == 200)) {
var rawData = request.responseText;
var cityTypes = eval("(" + rawData + ")");
var headings = new Array();
var row1Entries = new Array();
var i = 0;
for(var cityType in cityTypes) {
Object property names are city
categories like “top-5-cities”
for(var cityType in cityTypes) {
headings[i] = cityType;
row1Entries[i] = getBulletedList(cityTypes[cityType]);
i++;
}
var rows = [row1Entries];
var result = getTable(headings, rows);
ht lI t( ltR i lt)
Object property values are
arrays of city names (cities
htmlInsert(resultRegion, result);
}
}
48
y y (
that match the category)
Converting Maps: Client Code
(Continued)(Continued)
function getBulletedList(listItems) {
var list = "<ul>n";var list = "<ul>n";
for(var i=0; i<listItems.length; i++) {
list = list + " <li>" + listItems[i] + "</li>n";
}}
list = list + "</ul>"
return(list);
}}
49
Converting Maps:
HTML CodeHTML Code
<fieldset>
<legend>JSON Data: Automatic Conversion of Maps</legend><legend>JSON Data: Automatic Conversion of Maps</legend>
<form action="#">
<input type="button" value="Show City Types"
onclick='cityTypeList("show-city-types",onclick cityTypeList( show city types ,
"city-types")'/>
</form>
<p/>p/
<div id="city-types"></div>
</fieldset>
50
Converting Maps: Results
51
© 2010 Marty Hall
Sending JSON DataSending JSON Data
from Client to Server
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Using JSON.stringify
• Download json2.js
h // j /j 2 j– http://www.json.org/json2.js
– Or, start at http://www.json.org/js.html and follow links
at bottom of page
• Install in your project
– E.g., in Eclipse, drop in WebContent/scripts
Load json2 js in your HTML file– Load json2.js in your HTML file
• Call JSON.stringify on JavaScript object
– Produces string in JSON format representing objectg p g j
• Call escape on result
– URL-encode characters for transmission via HTTP
S d i POST t li t• Send in POST to client
– Data might be large, so POST is better than GET
53
Utility Function
function makeJsonString(object) {function makeJsonString(object) {
return(escape(JSON.stringify(object)));
}
54
Receiving JSON Objects on
ServerServer
• Pass string to JSONObject or JSONArray
constructor
– String jsonString = request.getParameter(…);
JSONArray myArray = new JSONArray(jsonString);– JSONArray myArray = new JSONArray(jsonString);
• Access elements with getBlah methods
– PrimitivesPrimitives
• getInt, getDouble, getString, getBoolean, isNull
• double d = myArray.getDouble(0);
S d t k th t th t ill b t f li t– Server needs to know the types that will be sent from client
– High-level
• getJSONObject, getJSONArray
55
Sending JSON to Server:
Client CodeClient Code
function randomCityTable(address, resultRegion) {
var data = "cityNames=" +var data = cityNames= +
makeJsonString(getRandomCities());
ajaxPost(address, data,
function(request) {function(request) {
showCityInfo2(request, resultRegion);
});
}}
This is the same showCityInfo2 function used earlier.
Takes an array of city objects and makes HTML tableTakes an array of city objects and makes HTML table
from their names, times, and populations.
56
Sending JSON to Server:
Client Code (Continued)Client Code (Continued)
var cityNames =
["New York", "Los Angeles", "Chicago", "Houston",[ New York , Los Angeles , Chicago , Houston ,
"Phoenix", "Philadelphia", "San Antonio", "San Diego",
"Dallas", "San Jose", "Detroit", "Jacksonville",
"Indianapolis", "San Francisco", "Columbus", "Austin",p , , , ,
"Memphis", "Fort Worth", "Baltimore", "Charlotte",
"El Paso", "Milwaukeee", "Boston", "Seattle",
"Washington DC", "Denver", "Louisville", "Las Vegas",
"Nashville", "Oklahoma City", "Miami"];
57
Sending JSON to Server:
Client Code (Continued)Client Code (Continued)
function getRandomCities() {
var randomCities = new Array();var randomCities new Array();
var j = 0;
for(var i=0; i<cityNames.length; i++) {
if(Math.random() < 0.25) {( () ) {
randomCities[j++] = cityNames[i];
}
}
return(randomCities);
}
58
Sending JSON to Server:
HTML CodeHTML Code
<script src="./scripts/ajax-utils.js"
type="text/javascript"></script>type text/javascript ></script>
<script src="./scripts/json-generation-examples.js"
type="text/javascript"></script>
<script src="./scripts/json2.js"p p j j
type="text/javascript"></script>
…
<fieldset>
<legend>JSON Data: Sending JSON <i>to</i>
Server</legend>
<form action="#">
<input type="button" value="Show Random Cities"<input type="button" value="Show Random Cities"
onclick='randomCityTable("show-cities-3",
"json-city-table-3")'/>
</form></form>
<p/>
<div id="json-city-table-3"></div>
</fieldset>59
Sending JSON to Server:
Server CodeServer Code
public class ShowCities3 extends ShowCities {
protected List<City> getCities(HttpServletRequest request) {p y g ( p q q ) {
String cityNames = request.getParameter("cityNames");
if ((cityNames == null) || (cityNames.trim().equals(""))) {
cityNames = "['New York', 'Los Angeles]";
}
try {
JSONArray jsonCityNames = new JSONArray(cityNames);
List<City> cities = new ArrayList<City>();st C ty c t es e ay st C ty ();
for(int i=0; i<jsonCityNames.length(); i++) {
City city =
CityUtils.getCityOrDefault(jsonCityNames.getString(i));
cities.add(city);
}
return(cities);
} catch(JSONException jse) {} catch(JSONException jse) {
return(CityUtils.findCities("top-5-cities"));
}
}60
Sending JSON to Server:
ResultsResults
61
© 2010 Marty Hall
Wrap-up
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Preview of Next Section:
JSON-RPCJSON-RPC
• Simpler designation of server-side resource
– Client-side code acts as if it is calling a server-side
function (not a URL)
• Simpler client side code• Simpler client-side code
– Client-side code passes and receives regular arguments
• Passing: no need to escape data or build param stringsg p p g
• Receiving: no need to use responseText or eval
• Simpler server-side code
S id d i d l– Server-side code receives and returns regular arguments
• Receiving: no need to call request.getParamter & convert
• Returning: results automatically converted with
JSONObject and JSONArray
63
Summary
• Building JSON from Java
– new JSONObject(bean)
– new JSONArray(arrayOrCollectionOfBeans, false)
new JSONObject(map)– new JSONObject(map)
• Outputting JSON String
– myJSONObject toString() myJSONArray toString()myJSONObject.toString(), myJSONArray.toString()
• When you do out.print, toString is invoked automatically
• Sending JSON to server
– escape(JSON.stringify(javaScriptObject))
• Receiving JSON on server
– new JSONObject(string) or new JSONArray(string)
– myArray.getString(i), myArray.getDouble(i), etc.
64
© 2010 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

Más contenido relacionado

La actualidad más candente

Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
 
How Scala code is expressed in the JVM
How Scala code is expressed in the JVMHow Scala code is expressed in the JVM
How Scala code is expressed in the JVMKoichi Sakata
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code ExamplesNaresh Chintalcheru
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantesmikaelbarbero
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeletonIram Ramrajkar
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
Dart structured web apps
Dart   structured web appsDart   structured web apps
Dart structured web appschrisbuckett
 
13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 

La actualidad más candente (17)

Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
How Scala code is expressed in the JVM
How Scala code is expressed in the JVMHow Scala code is expressed in the JVM
How Scala code is expressed in the JVM
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
JDK Power Tools
JDK Power ToolsJDK Power Tools
JDK Power Tools
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Hibernate
Hibernate Hibernate
Hibernate
 
Dart structured web apps
Dart   structured web appsDart   structured web apps
Dart structured web apps
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
13 java beans
13 java beans13 java beans
13 java beans
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 

Destacado (18)

Agent technology for e commerce-recommendation systems
Agent technology for e commerce-recommendation systemsAgent technology for e commerce-recommendation systems
Agent technology for e commerce-recommendation systems
 
0321146182
03211461820321146182
0321146182
 
Big data tutorial_part4
Big data tutorial_part4Big data tutorial_part4
Big data tutorial_part4
 
Httpclient tutorial
Httpclient tutorialHttpclient tutorial
Httpclient tutorial
 
Net framework
Net frameworkNet framework
Net framework
 
Android+ax+app+wcf
Android+ax+app+wcfAndroid+ax+app+wcf
Android+ax+app+wcf
 
Soap pt1
Soap pt1Soap pt1
Soap pt1
 
Andrei shakirin rest_cxf
Andrei shakirin rest_cxfAndrei shakirin rest_cxf
Andrei shakirin rest_cxf
 
B14200
B14200B14200
B14200
 
13 pv-do es-18-bigdata-v3
13 pv-do es-18-bigdata-v313 pv-do es-18-bigdata-v3
13 pv-do es-18-bigdata-v3
 
Introduction to visual studio and c sharp
Introduction to visual studio and c sharpIntroduction to visual studio and c sharp
Introduction to visual studio and c sharp
 
Show loader to open url in web view
Show loader to open url in web viewShow loader to open url in web view
Show loader to open url in web view
 
Culbert recommender systems
Culbert recommender systemsCulbert recommender systems
Culbert recommender systems
 
Recommender systems session b
Recommender systems session bRecommender systems session b
Recommender systems session b
 
Chapter 02 collaborative recommendation
Chapter 02   collaborative recommendationChapter 02   collaborative recommendation
Chapter 02 collaborative recommendation
 
Soap toolkits
Soap toolkitsSoap toolkits
Soap toolkits
 
Sqlite tutorial
Sqlite tutorialSqlite tutorial
Sqlite tutorial
 
Vortrag ralph behrens_ibm-data
Vortrag ralph behrens_ibm-dataVortrag ralph behrens_ibm-data
Vortrag ralph behrens_ibm-data
 

Similar a Json generation

Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Ramamohan Chokkam
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxtutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags AdvancedAkramWaseem
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
15 expression-language
15 expression-language15 expression-language
15 expression-languagesnopteck
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basicssnopteck
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
Ajax Basics 2
Ajax Basics 2Ajax Basics 2
Ajax Basics 2bhuvanann
 
Ajax Basics 1
Ajax Basics 1Ajax Basics 1
Ajax Basics 1bhuvanann
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 

Similar a Json generation (20)

Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
 
Java script core
Java script coreJava script core
Java script core
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
15 expression-language
15 expression-language15 expression-language
15 expression-language
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
JSF 2.0 Preview
JSF 2.0 PreviewJSF 2.0 Preview
JSF 2.0 Preview
 
Ajax Basics 2
Ajax Basics 2Ajax Basics 2
Ajax Basics 2
 
Ajax Basics 1
Ajax Basics 1Ajax Basics 1
Ajax Basics 1
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 

Último

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 

Último (20)

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 

Json generation

  • 1. © 2010 Marty Hall Automatically Generating JSON from Java ObjectsJava Objects Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/ajax.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. http://courses.coreservlets.com/Course Materials/ajax.html © 2010 Marty Hall For live Ajax & GWT training, see training t htt // l t /courses at http://courses.coreservlets.com/. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available atMore Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. C d l d d t ht b M t H ll Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. • Courses developed and taught by Marty Hall – Java 6, servlets/JSP (intermediate and advanced), Struts, JSF 1.x, JSF 2.0, Ajax, GWT 2.0 (with GXT), custom mix of topics – Ajax courses can concentrate on 1 library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, Google Closure) or survey several • Courses developed and taught by coreservlets.com experts (edited by Marty) – Spring, Hibernate/JPA, EJB3, Web Services, Ruby/Rails Contact hall@coreservlets.com for details
  • 2. Topics in This Section • Using org.json Java utilities – Building JSON object from bean – Building JSON array from Java array or List Building JSON object from Map– Building JSON object from Map – Other JSON-generation utilities • Using json2.js JavaScript utilitiesUsing json2.js JavaScript utilities – Sending JSON objects to server 4 © 2010 Marty Hall Intro and Setup Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 3. Using MVC to Build JSON • Last section: used MVC to build JSON – Advantages • Requires no special server software • You have full control over resultYou have full control over result – Disadvantages • Tedious for complex data structures Oft i k l d f h ill d t• Often requires knowledge of how server will use data • This section: turning Java into JSON – AdvantagesAdvantages • Can generate complex data easily • Builds real objects so server can decide what to do Di d– Disadvantages • Requires JSON-specific server software • Sometimes builds objects with unneeded data in them6 Installing the org.json.* Utilities • Download – http://www.json.org/java/json.zip • Or start at http://www.json.org/java/ and follow link that says “Free source code is available”.y • Install – Unzip to get org/json/*.java – Put into src folder of Eclipse • Create new package org.json, then copy files there – They do not supply a JAR file but you could easily build– They do not supply a JAR file, but you could easily build one yourself, then put JAR file in WEB-INF/lib • Built org.json-utils.jar and put online at coreservlets.com • Documentation – http://www.json.org/java/ 7
  • 4. Configuring Eclipse Project Used only in last example. Available for download at http://www.json.org/json2.js. You can also get compressed version; see http://www.json.org/js.html.version; see http://www.json.org/js.html. Used in all examples. Available for download at http://courses coreservlets com/Course-Materials/ajax html 8 http://courses.coreservlets.com/Course-Materials/ajax.html Downloaded latest .java files from http://www.json.org/java/, compiled, and put resultant .class files in JAR file. Or, you can put .java files from http://www.json.org/java/ directly in src/org.json. Other JSON-Generation SoftwareSoftware • org.json utilities (used in this tutorial) Wid l d– Widely used • Used within other utilities (e.g., JSON-RPC) – Limited power Alt ti• Alternatives – Google Gson • Better support for generics htt // d l / / l /• http://code.google.com/p/google-gson/ – JSON Taglib • More usable directly from JSP http://json taglib sourceforge net/• http://json-taglib.sourceforge.net/ – VRaptor • Uses annotations for much of the work • http://vraptor org/ajax html• http://vraptor.org/ajax.html – Many more • See “Java” entry at http://json.org/ 9
  • 5. © 2010 Marty Hall Supporting Java CodeSupporting Java Code (Used in All Examples) Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Main Bean: City.java • Constructor public City(String name, int timeZone, int pop) { setName(name); setTimeZone(timeZone); setPop(pop);setPop(pop); } • Getter methods – getName – getTime, getTimeZone • Assumes server is in US east coasts subtracts 0-3 hoursAssumes server is in US east coasts, subtracts 0 3 hours based on time zone – getPop Raw population as an int• Raw population as an int – getPopulation • Formatted population as a String with commas11
  • 6. Utilities for Finding Beans: CityUtils javaCityUtils.java • Map that associates city name with City private static Map<String,City> biggestAmericanCities = new HashMap<String,City>(); • Populate it with largest US cities L k f ti• Lookup functions public static City getCity(String name) { name = name.toUpperCase(); return(biggestAmericanCities.get(name)); } 12 Utilities for Finding Beans: CityUtils java ContinuedCityUtils.java Continued • Map that associates category of cities with icity names private static Map<String,String[]> cityTypeMap; • Lookup function public static List<City> findCities(String cityType) { String[] cityNames = cityTypeMap get(cityType);String[] cityNames cityTypeMap.get(cityType); if (cityNames == null) { String[] twoCities = { "New York", "Los Angeles" }; cityNames = twoCities; } List<City> cities = new ArrayList<City>(); for(String cityName: cityNames) { cities add(getCity(cityName));cities.add(getCity(cityName)); } return(cities); }13
  • 7. Parent Servlet Class: ShowCities javaShowCities.java public abstract class ShowCities extends HttpServlet { public void doGet(HttpServletRequest request,public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setContentType("text/javascript"); List<City> cities = getCities(request); outputCities(cities, request, response); } protected List<City> getCities(HttpServletRequest request) {protected List<City> getCities(HttpServletRequest request) { String cityType = request.getParameter("cityType"); return(CityUtils.findCities(cityType)); }} 14 Parent Servlet Class: ShowCities java ContinuedShowCities.java Continued public void doPost(HttpServletRequest request, HttpServletResponse response)HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public abstract void outputCities (List<City> cities, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; }} 15
  • 8. © 2010 Marty Hall General Approach Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Steps for Servlet Using JSON UtilitiesUtilities • Set normal response headers tH d f P d C h C t l– response.setHeader for Pragma and Cache-Control • Set Content-Type to text/javascript – response.setContentType("text/javascript"); • Get PrintWriter in normal manner – PrintWriter out = response.getWriter • Get result as bean array or Map• Get result as bean, array, or Map – Call normal business logic code • Turn Java object into JSONObject – JSONObject result = new JSONObject(bean); – JSONArray result = new JSONArray(arrayOfBeans, false); – JSONObject result = new JSONObject(map);j j ( p) • Output JSONObject with print – out.print(result); 17
  • 9. Steps for Using JSON Utilities: Sample Servlet CodeSample Servlet Code public void doPost(HttpServletRequest request, HttpServletResponse response)HttpServletResponse response) throws ServletException, IOException { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setContentType("text/javascript"); PrintWriter out = response.getWriter(); SomeBean javaResult = callSomeBusinessLogic(…); JSONObject jsonResult = new JSONObject(javaResult); out.print(jsonResult);p (j ); } These two lines are the only ones that typically change f li ti t li ti Oth li t tl i 18 from application to application. Other lines stay exactly as is. © 2010 Marty Hall Turning Java BeansTurning Java Beans into JSONObjectj Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 10. Turning Beans into JSON • org.json defines JSONObject I S i h d b ild JSON f– Its toString method builds JSON format • Most important constructor takes a bean – JSONObject json = new JSONObject(myBean);JSONObject json new JSONObject(myBean); • Second arg of “true” means to include superclass info – Result • Uses reflection on myBean to find all public methods of the• Uses reflection on myBean to find all public methods of the form getBlah (any return type) or isBlah (boolean return) • Calls each getter method • If myBean has getFoo and getBar, it builds object of theIf myBean has getFoo and getBar, it builds object of the form { "foo": "getFoo() result", "bar": "getBar() result"} • Other capabilities Can turn Map into JSONObject (keys become properties)– Can turn Map into JSONObject (keys become properties) – Can add properties one at a time with “put” 20 JSONObject from Bean: Example CodeExample Code package coreservlets; import org.json.*; public class CityTest1 {public class CityTest1 { public static void main(String[] args) { City sf = CityUtils.getCity("San Francisco"); JSONObj t fJSON JSONObj t( f)JSONObject sfJSON = new JSONObject(sf); System.out.println("JSON version of SF is:n" + sfJSON); } } 21 Note: toString is automatically called when you print an Object in Java. It is the toString method of JSONObject that builds the JSON representation.
  • 11. JSONObject from Bean: Example ResultExample Result JSON version of SF is: {"time": "06:00:55 AM"{"time": "06:00:55 AM", "name": "San Francisco", "timeZone": -3, "pop": 744041, "population": " 744,041"} • (White space added for readability) 22 Building Arrays of JSON Info • org.json defines JSONArray – Its toString method outputs array in JSON format • Most important constructors JSONA (j A O C ll i )– new JSONArray(javaArrayOrCollection) • Assumes javaArrayOrCollection contains primitives, Strings, or JSONObjects – new JSONArray(javaArrayOrCollection, false) • Assumes javaArrayOrCollection contains beans that should be converted as in previous section, but you don’tp , y want to include superclass info – new JSONArray(javaArrayOrCollection, true) • Assumes javaArrayOrCollection contains beans that• Assumes javaArrayOrCollection contains beans that should be converted as in previous section, but you do want to include superclass info 23
  • 12. JSONArray: Example Code package coreservlets; import org.json.*; import java.util.*; public class CityTest2 { public static void main(String[] args) { List<City> biggestUSCities =List<City> biggestUSCities CityUtils.findCities("top-5-cities"); JSONArray citiesJSON = new JSONArray(biggestUSCities, false);e JSO ay(b ggestUSC t es, a se); System.out.println("JSON version of biggest " + "US cities is:n" + citiesJSON);); } } 24 JSONArray: Example Result JSON version of biggest US cities is: [{"time":"09:14:16 AM" "name":"New York"[{"time":"09:14:16 AM", "name":"New York", "timeZone":0,"pop":8250567,"population":"8,250,567"}, {"time":"06:14:16 AM", "name":"Los Angeles", "timeZone": 3 "pop":3849368 "population":"3 849 368"}"timeZone":-3,"pop":3849368,"population":"3,849,368"}, {"time":"08:14:16 AM", "name":"Chicago", "timeZone":-1,"pop":2873326,"population":"2,873,326"}, {"ti " "08 14 16 AM" " " "H t "{"time":"08:14:16 AM", "name":"Houston", "timeZone":-1,"pop":2144491,"population":"2,144,491"}, {"time":"07:14:16 AM", "name":"Phoenix", "ti Z " 2 " " 1512986 " l ti " "1 512 986"}]"timeZone":-2,"pop":1512986,"population":"1,512,986"}] • (White space added for readability)(White space added for readability) 25
  • 13. © 2010 Marty Hall C i M l dComparing Manual and Automatic JSON Generation Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.26 Manual Generation: Server Code (Servlet)(Servlet) public class ShowCities1 extends ShowCities { public void outputCities(List<City> citiespublic void outputCities(List<City> cities, HttpServletRequest request, HttpServletResponse response) throws ServletException IOException {throws ServletException, IOException { request.setAttribute("cities", cities); String outputPage = "/WEB INF/ lt / iti j j ""/WEB-INF/results/cities-json.jsp"; RequestDispatcher dispatcher = request.getRequestDispatcher(outputPage); di t h i l d ( t )dispatcher.include(request, response); } } 27
  • 14. Manual Generation: Server Code (JSP)(JSP) { headings: ["City", "Time", "Population"], cities: [["${cities[0] name}" "${cities[0] time}"cities: [["${cities[0].name}", "${cities[0].time}", "${cities[0].population}"], ["${cities[1].name}", "${cities[1].time}", "${cities[1].population}"], ["${cities[2].name}", "${cities[2].time}", "${cities[2].population}"], ["${cities[3].name}", "${cities[3].time}", "${cities[3].population}"], ["${cities[4].name}", "${cities[4].time}",[ ${ [ ] } , ${ [ ] } , "${cities[4].population}"]] } 28 Manual Generation: Client Code function cityTable1(address, inputField, resultRegion) { var data = "cityType=" + getValue(inputField);var data = "cityType=" + getValue(inputField); ajaxPost(address, data, function(request) { showCityInfo1(request resultRegion);showCityInfo1(request, resultRegion); }); } • Note: – ajaxPost shown in previous tutorial sectionajaxPost shown in previous tutorial section • Sends data via POST and passes result to handler function 29
  • 15. Manual Generation: Client Code (Continued)(Continued) // Data that arrives is JSON object with two properties: // headings (an array of strings for the th elements)// - headings (an array of strings for the th elements) // - cities (an array of array of strings // matching the heading names) function showCityInfo1(request, resultRegion) { if ((request.readyState == 4) && ( t t t 200)) {(request.status == 200)) { var rawData = request.responseText; var data = eval("(" + rawData + ")"); t bl tT bl (d t h di d t iti )var table = getTable(data.headings, data.cities); htmlInsert(resultRegion, table); } } 30 Manual Generation: HTML Code <fieldset> <legend>JSON Data: Original MVC Approach</legend>g g pp / g <form action="#"> <label for="city-type-1">City Type:</label> <select id="city-type-1"> /<option value="top-5-cities">Largest Five US Cities</option> <option value="second-5-cities">Second Five US Cities</option> … </select>/se ect <br/> <input type="button" value="Show Cities" onclick='cityTable1("show-cities-1", "city-type-1", /"json-city-table-1")'/> </form> <p/> <div id="json-city-table-1"></div><div id json city table 1 ></div> </fieldset> 31
  • 16. Manual Generation: Results 32 Manual Generation: Pros and ConsPros and Cons • Advantages – Requires no JSON-specific software on server – Java code is moderately simple Client code is simple– Client code is simple • Disadvantages – JSP code is complexJSP code is complex – JSP code cannot adapt to arbitrary number of cities • This can be fixed with JSTL – see next tutorial section – Server code needs to know a lot about how client code will use results. Server code essentially pre-processed the data and put it in form ready for presentation.p y p • If you are going to do that, why bother with data-centric Ajax? Why not just send HTML table from the server? 33
  • 17. Automatic Generation: Server Code (Servlet)Code (Servlet) public class ShowCities2 extends ShowCities { public void outputCities(List<City> citiespublic void outputCities(List<City> cities, HttpServletRequest request, HttpServletResponse response) throws ServletException IOException {throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(new JSONArray(cities, false)); }} } 34 Automatic Generation: Server Code (JSP)Code (JSP) • None! 35
  • 18. Automatic Generation: Client CodeCode function cityTable2(address, inputField, resultRegion) { var data = "cityType=" + getValue(inputField);var data = "cityType=" + getValue(inputField); ajaxPost(address, data, function(request) { showCityInfo2(request resultRegion);showCityInfo2(request, resultRegion); }); } • Note: – Only difference from previous example is that result isOnly difference from previous example is that result is passed to showCityInfo2 instead of ShowCityInfo1 36 Automatic Generation: Client Code (Continued)Code (Continued) // Data that arrives is an array of city objects. // City objects contain (among other things)// City objects contain (among other things) // name, time, and population properties. function showCityInfo2(request, resultRegion) { if ((request.readyState == 4) && (request.status == 200)) { var rawData = request.responseText; var cities = eval("(" + rawData + ")");var cities = eval( ( + rawData + ) ); var headings = ["City", "Time", "Population"]; var rows = new Array(); for(var i=0; i<cities.length; i++) { var city = cities[i]; rows[i] = [city.name, city.time, city.population]; } t bl tT bl (h di )var table = getTable(headings, rows); htmlInsert(resultRegion, table); } }37
  • 19. Automatic Generation: HTML CodeHTML Code <fieldset> <legend>JSON Data: Automatic Conversion of Lists</legend>g / g <form action="#"> <label for="city-type-2">City Type:</label> <select id="city-type-2"> /<option value="top-5-cities">Largest Five US Cities</option> <option value="second-5-cities">Second Five US Cities</option> … </select>/se ect <br/> <input type="button" value="Show Cities" onclick='cityTable2("show-cities-2", "city-type-2", /"json-city-table-2")'/> </form> <p/> <div id="json-city-table-2"></div><div id json city table 2 ></div> </fieldset> 38 Automatic Generation: Results 39
  • 20. Automatic Generation: Pros and ConsPros and Cons • Advantages J d i i l– Java code is very simple – No JSP whatsoever – Server code can adapt to arbitrary number of citiesp y – Server code does not need to know how client code will use the result – Client code has “real” data so can do logic based on itClient code has real data so can do logic based on it • Disadvantages – Requires JSON-specific software on server – Client code is more complex • It needs to extract data from objects before sending it to table-building function – Extra fields were sent • Client did not use timeZone and pop properties, but they were sent anyway40 © 2010 Marty Hall Turning Java MapsTurning Java Maps into JSONObjectj Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 21. Building JSONObject from Map • Most important JSONObject constructors – new JSONObject(bean) • Uses reflection on myBean to find all public methods of the form getBlah (any return type) or isBlah (boolean return)g ( y yp ) ( ) • Calls each getter method • If myBean has getFoo and getBar, it builds object of the form { "foo": "getFoo() result", "bar": "getBar() result"}form { foo : getFoo() result , bar : getBar() result } – new JSONObject(bean, true) • Same as above but includes inherited methods Oth t t• Other constructors – new JSONObject(map) • Map keys become JSON property namesMap keys become JSON property names – new JSONObject(string) • Useful when passing JSON to the server42 JSONObject from Map: Example CodeExample Code package coreservlets; import org.json.*; import java.util.*; public class CityTest3 { public static void main(String[] args) { M <St i St i []> itiMap<String,String[]> cities = CityUtils.getCityTypeMap(); JSONObject citiesJSON = ( )new JSONObject(cities); System.out.println("JSON version of map of " + "US cities is:n" + citiesJSON); } }43
  • 22. JSONObject from Map: Example ResultExample Result JSON version of map of US cities is: {"superbowl-hosts":{ superbowl hosts : ["Phoenix","Miami", "Detroit","Jacksonville","Houston"], "top-5-cities":top 5 cities : ["New York","Los Angeles", "Chicago","Houston","Phoenix"], "cities-starting-with-s":cities starting with s : ["San Antonio","San Diego", "San Jose","San Francisco","Seattle"], "second-5-cities":seco d 5 c t es : ["Philadelphia","San Antonio", "San Diego","Dallas","San Jose"]} • (White space added for readability) 44 Converting Maps: Server Code public class ShowCityTypes extends HttpServlet { public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response setHeader("Cache-Control" "no-cache");response.setHeader( Cache Control , no cache ); response.setHeader("Pragma", "no-cache"); response.setContentType("text/javascript"); PrintWriter out = response.getWriter();PrintWriter out response.getWriter(); JSONObject cityTypes = new JSONObject(CityUtils.getCityTypeMap()); out.println(cityTypes);out.p t (c ty ypes); } 45
  • 23. Converting Maps: Server Code (Continued)(Continued) public void doPost(HttpServletRequest requestpublic void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request response);doGet(request, response); } } 46 Converting Maps: Client Code function cityTypeList(address, resultRegion) { ajaxPost(address nullajaxPost(address, null, function(request) { showCityTypeInfo(request, resultRegion); });}); } // Data that arrives is an object where the // properties are city categories and the // associated values are arrays of city names.// assoc ated a ues a e a ays o c ty a es. 47
  • 24. Converting Maps: Client Code (Continued)(Continued) function showCityTypeInfo(request, resultRegion) { if ((request.readyState == 4) &&if ((request.readyState 4) && (request.status == 200)) { var rawData = request.responseText; var cityTypes = eval("(" + rawData + ")"); var headings = new Array(); var row1Entries = new Array(); var i = 0; for(var cityType in cityTypes) { Object property names are city categories like “top-5-cities” for(var cityType in cityTypes) { headings[i] = cityType; row1Entries[i] = getBulletedList(cityTypes[cityType]); i++; } var rows = [row1Entries]; var result = getTable(headings, rows); ht lI t( ltR i lt) Object property values are arrays of city names (cities htmlInsert(resultRegion, result); } } 48 y y ( that match the category) Converting Maps: Client Code (Continued)(Continued) function getBulletedList(listItems) { var list = "<ul>n";var list = "<ul>n"; for(var i=0; i<listItems.length; i++) { list = list + " <li>" + listItems[i] + "</li>n"; }} list = list + "</ul>" return(list); }} 49
  • 25. Converting Maps: HTML CodeHTML Code <fieldset> <legend>JSON Data: Automatic Conversion of Maps</legend><legend>JSON Data: Automatic Conversion of Maps</legend> <form action="#"> <input type="button" value="Show City Types" onclick='cityTypeList("show-city-types",onclick cityTypeList( show city types , "city-types")'/> </form> <p/>p/ <div id="city-types"></div> </fieldset> 50 Converting Maps: Results 51
  • 26. © 2010 Marty Hall Sending JSON DataSending JSON Data from Client to Server Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Using JSON.stringify • Download json2.js h // j /j 2 j– http://www.json.org/json2.js – Or, start at http://www.json.org/js.html and follow links at bottom of page • Install in your project – E.g., in Eclipse, drop in WebContent/scripts Load json2 js in your HTML file– Load json2.js in your HTML file • Call JSON.stringify on JavaScript object – Produces string in JSON format representing objectg p g j • Call escape on result – URL-encode characters for transmission via HTTP S d i POST t li t• Send in POST to client – Data might be large, so POST is better than GET 53
  • 27. Utility Function function makeJsonString(object) {function makeJsonString(object) { return(escape(JSON.stringify(object))); } 54 Receiving JSON Objects on ServerServer • Pass string to JSONObject or JSONArray constructor – String jsonString = request.getParameter(…); JSONArray myArray = new JSONArray(jsonString);– JSONArray myArray = new JSONArray(jsonString); • Access elements with getBlah methods – PrimitivesPrimitives • getInt, getDouble, getString, getBoolean, isNull • double d = myArray.getDouble(0); S d t k th t th t ill b t f li t– Server needs to know the types that will be sent from client – High-level • getJSONObject, getJSONArray 55
  • 28. Sending JSON to Server: Client CodeClient Code function randomCityTable(address, resultRegion) { var data = "cityNames=" +var data = cityNames= + makeJsonString(getRandomCities()); ajaxPost(address, data, function(request) {function(request) { showCityInfo2(request, resultRegion); }); }} This is the same showCityInfo2 function used earlier. Takes an array of city objects and makes HTML tableTakes an array of city objects and makes HTML table from their names, times, and populations. 56 Sending JSON to Server: Client Code (Continued)Client Code (Continued) var cityNames = ["New York", "Los Angeles", "Chicago", "Houston",[ New York , Los Angeles , Chicago , Houston , "Phoenix", "Philadelphia", "San Antonio", "San Diego", "Dallas", "San Jose", "Detroit", "Jacksonville", "Indianapolis", "San Francisco", "Columbus", "Austin",p , , , , "Memphis", "Fort Worth", "Baltimore", "Charlotte", "El Paso", "Milwaukeee", "Boston", "Seattle", "Washington DC", "Denver", "Louisville", "Las Vegas", "Nashville", "Oklahoma City", "Miami"]; 57
  • 29. Sending JSON to Server: Client Code (Continued)Client Code (Continued) function getRandomCities() { var randomCities = new Array();var randomCities new Array(); var j = 0; for(var i=0; i<cityNames.length; i++) { if(Math.random() < 0.25) {( () ) { randomCities[j++] = cityNames[i]; } } return(randomCities); } 58 Sending JSON to Server: HTML CodeHTML Code <script src="./scripts/ajax-utils.js" type="text/javascript"></script>type text/javascript ></script> <script src="./scripts/json-generation-examples.js" type="text/javascript"></script> <script src="./scripts/json2.js"p p j j type="text/javascript"></script> … <fieldset> <legend>JSON Data: Sending JSON <i>to</i> Server</legend> <form action="#"> <input type="button" value="Show Random Cities"<input type="button" value="Show Random Cities" onclick='randomCityTable("show-cities-3", "json-city-table-3")'/> </form></form> <p/> <div id="json-city-table-3"></div> </fieldset>59
  • 30. Sending JSON to Server: Server CodeServer Code public class ShowCities3 extends ShowCities { protected List<City> getCities(HttpServletRequest request) {p y g ( p q q ) { String cityNames = request.getParameter("cityNames"); if ((cityNames == null) || (cityNames.trim().equals(""))) { cityNames = "['New York', 'Los Angeles]"; } try { JSONArray jsonCityNames = new JSONArray(cityNames); List<City> cities = new ArrayList<City>();st C ty c t es e ay st C ty (); for(int i=0; i<jsonCityNames.length(); i++) { City city = CityUtils.getCityOrDefault(jsonCityNames.getString(i)); cities.add(city); } return(cities); } catch(JSONException jse) {} catch(JSONException jse) { return(CityUtils.findCities("top-5-cities")); } }60 Sending JSON to Server: ResultsResults 61
  • 31. © 2010 Marty Hall Wrap-up Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Preview of Next Section: JSON-RPCJSON-RPC • Simpler designation of server-side resource – Client-side code acts as if it is calling a server-side function (not a URL) • Simpler client side code• Simpler client-side code – Client-side code passes and receives regular arguments • Passing: no need to escape data or build param stringsg p p g • Receiving: no need to use responseText or eval • Simpler server-side code S id d i d l– Server-side code receives and returns regular arguments • Receiving: no need to call request.getParamter & convert • Returning: results automatically converted with JSONObject and JSONArray 63
  • 32. Summary • Building JSON from Java – new JSONObject(bean) – new JSONArray(arrayOrCollectionOfBeans, false) new JSONObject(map)– new JSONObject(map) • Outputting JSON String – myJSONObject toString() myJSONArray toString()myJSONObject.toString(), myJSONArray.toString() • When you do out.print, toString is invoked automatically • Sending JSON to server – escape(JSON.stringify(javaScriptObject)) • Receiving JSON on server – new JSONObject(string) or new JSONArray(string) – myArray.getString(i), myArray.getDouble(i), etc. 64 © 2010 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x, JSF 2.0, Struts, Ajax, GWT 2.0, GXT, Spring, Hibernate/JPA, Java 5, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.