注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

姑射道人的博客

博客新地址:nixuchen.com

 
 
 

日志

 
 

convert XML to JSON and back  

2014-07-15 17:53:51|  分类: java |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

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 to the rescue!

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.

Putting it to work

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!

 

  评论这张
 
阅读(901)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017