Reputation: 1450
I want to use the com.ibm.commons.util.io.json.* library which comes with the XPages runtime to serialise a Java Bean into JSON.
The question is can it do it automatically by just passing it the object - like you can with the Google library - http://code.google.com/p/google-gson/ or do you need to construct the JSON manually by which I mean passing the individual properties to construct the JSON.
Having trouble locating the documentation for this library, though I have seen some examples:
http://www-10.lotus.com/ldd/ddwiki.nsf/dx/Sending_requests_in_Java_dds10
Ideally we dont want to use a 3rd party library, even though it works great, because we need to modify the java security properties file which in turn gets wiped if the server gets upgraded.
Upvotes: 2
Views: 2167
Reputation: 673
The com.ibm.commons.util.io.json library is a genric library for converting JSON representations to Java objects, back and forth. By generic, I mean that it uses a factory to both browse and update the Java objects (see: JsonFactory). By implementing such a factory, and implementing the getter/setters for all the properties, one can serialize/deserialize any kind of objects. The JSON library is equiped with a set of predefined factories:
We don't have a factory for JavaBeans per say, but implementing such a factory should not be a big deal.
Upvotes: 13
Reputation: 1665
The ibm commons library for json works by constructing an object, then adding json properties to the object. It can not auto-serialize an object, and works really only with primitive data types.
I've attached some SSJS code to illustrate how to work with the class. It assumes recordMap is a java map instance with some beans in it, and each bean has 5 fields named fieldName1 through fieldName5. The code iterates through each bean in the map, retrieves the 5 fields, convert the values to JSON, then pushes them into array. Finally the array is put inside another json object that includes the count, and the array itself.
var jsonObjArr = [];
var itr:java.util.Iterator = recordMap.keySet().iterator();
while (itr.hasNext()) {
var record = recordMap.get(itr.next());
var jsonObj:com.ibm.commons.util.io.json.JsonJavaObject =
new com.ibm.commons.util.io.json.JsonJavaObject();
jsonObj.putJsonProperty("fieldName1", record.getFieldName1());
jsonObj.putJsonProperty("fieldName2", record.getFieldName2());
jsonObj.putJsonProperty("fieldName3", record.getFieldName3());
jsonObj.putJsonProperty("fieldName4", record.getFieldName4());
jsonObj.putJsonProperty("fieldName5", record.getFieldName5());
jsonObj.putJsonProperty("fieldName6", record.getFieldName6());
jsonObjArr.push(com.ibm.commons.util.io.json.JsonGenerator
.toJson(com.ibm.commons.util.io.json.JsonJavaFactory.instanceEx, empr));
};
var jsonString = "{" +
"count:" + @Text(jsonObjArr.length) + "," +
"employees:" + "[" + jsonObjArr.join(",") + "]" +
"}";
return jsonString;
Hope this helps..
Upvotes: 5