In my Connect 2013 session my main demo app was returning XML for some things and JSON for other things. When you are developing a REST api, it is important that you are supporting the data format that your clients are going to get the most out of. This probably means that you will pick one and wait until you are asked for the other. What if you could easily support both right out of the gate… with virtually no extra effort?
JSON.org is the go to place for all things JSON. They have a listing of support libraries for almost every language which makes it easy to add JSON support to any kind of app. For my REST talk I used the Java libraries that you can get here added to a Notes Database as a Script Library and regular java resources that I can use from an XPage.
Once you get the code downloaded imported into your Notes database, the easiest thing you can do to start playing with it is to convert a normal Notes document into JSON, maybe for returning in a REST api.
First, you need to get some XML. Luckily the Java version of the NotesDocument class has a function called generateXML() which returns a string with the DXL for the document. For some clients, you can just return that. Once you have the XML, the JSON.org library contains an object called XML that contains a static method called toJSONObject() which will take that XML string and create a JSONObjectwhich has a function called toString(). The toString() function will return the JSON version of the original XML. So basically with this short bit of code:
String xml = doc.generateXML(); String JSON = org.json.XML.toJSONObject(xml).toString();
The JSON.org library also makes it really easy to go the other way too so you clients and send XML or JSON and you can handle both with ease. On top of all that the library contains a ton of other tools that make working with JSON really easy.
Anyone else have some cool tips for JSON or XML? Let me know!