JSON
JavaScript Object Notation (JSON) is becoming increasingly popular as an integration format. Its lightweight, since it requires no parser, and its widely supported through a vibrant open-source initiative that provides JSON libraries for most major development tools and languages.
Converting Models to and from JSON
The Model Interface allows you to convert to the JSON format with the toJSONObject() method. Here is a quick example pulled from the Bookstore tutorial found in the Training Guide:
ModelDataService mds = Services.get(ModelDataService.
class
);
Book book;
try
{
book = mds.readById( ... );
}
catch
(Exception e) { ... }
return
book.toJSONObject();
To perform the reverse (convert a JSONObject to a Model), or convert (to or from) more than one instance of a Model at a time, you will want to use JSONService. Here is the short example pulled from the Bookstore tutorial:
// JSONObject bookObj;
// ...
JSONService js = Services.get(JSONService.
class
);
Book book = js.jsonToModel(bookObj, Book.
class
, getPlatformUserProfile());
Using JSON in Rest Resources
One Network Platform uses Jersey, which is an implementation of JAX-RS (Java API for RESTful Web Services). The UI layer of every module is done primarily with ExtJS, a rich cross-browser JavaScript library. It uses JSON as the communication format with the server, and rest resources are the endpoints of those requests. Below is an example taken from SampleResource.java that comes with every new module:
@Path
(
"/sample"
)
public
class
SampleResource {
@GET
@Produces
({
"application/json"
})
public
JSONObject getSample() {
JSONObject result =
new
JSONObject();
result.put(
"sample"
,
"hello world"
);
return
result;
}
}
As you can see, annotations in JAX-RS are used to describe a web resource. This particular resource endpoint uses the GET method, takes no parameters, and returns a JSONObject. To locate a resource endpoint, you must use the URL '/oms/rest/<module prefix>/<path to resource>/<path to method>'. In this example, the URL would be: '/oms/rest/ZBKS/sample'.
In ExtJS, we typically use Ext.Ajax to make requests. Here's a snippet that would call the getSample() method inside SampleResource:
Ext.Ajax.request({
url:
'/oms/rest/ZBKS/sample'
,method:
'GET'
,callback: function(options, success, response) {
if
(success) {
var json = Ext.decode(response.responseText);
alert(json.sample);
// pops up alert box with: "hello world"
}
}
,scope:
this
});