25-08-2017, 09:32 PM
Automatically Generating JSON from Java Objects
utomatically.pdf (Size: 1.69 MB / Downloads: 167)
Using MVC to Build JSON
• Last section: used MVC to build JSON
– Advantages
• Requires no special server software
• You have full control over result
– Disadvantages
• Tedious for complex data structures
• Often requires knowledge of how server will use data
• This section: turning Java into JSON
– Advantages
• Can generate complex data easily
• Builds real objects so server can decide what to do
– Disadvantages
• Requires JSON-specific server software
6 • Sometimes builds objects with unneeded data in them
Other JSON-Generation
Software
• org.json utilities (used in this tutorial)
– Widely used
• Used within other utilities (e.g., JSON-RPC)
– Limited power
• Alternatives
– Google Gson
• Better support for generics
• http://code.googlep/google-gson/
– JSON Taglib
• More usable directly from JSP
• http://json-taglib.sourceforge
– VRaptor
• Uses annotations for much of the work
• http://vraptorajax.html
– Many more
• See “Java” entry at http://json
Turning Beans into JSON
• org.json defines JSONObject
– Its toString method builds JSON format
• Most important constructor takes a bean
– 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
form getBlah (any return type) or isBlah (boolean return)
• Calls each getter method
• If 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 add properties one at a time with “put”
Building Arrays of JSON Info
• org.json defines JSONArray
– Its toString method outputs array in JSON format
• Most important constructors
– 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’t
want to include superclass info
– new JSONArray(javaArrayOrCollection, true)
• Assumes javaArrayOrCollection contains beans that
should be converted as in previous section, but you do
want to include superclass info