打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
java xml转json

第一种:

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
public class Test {
public static void main(String[] args) throws Exception {
String xml = "<root><name type='type'>zhaipuhong</name><gender>male</gender><birthday><year>1970</year><month>12</month><day>17</day></birthday></root>";
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read( xml );
System.out.println( json.toString(2) );
}
}
转换结果:<name type='type'>的属性没了
 
第二种:
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
public class Test {
public static void main(String[] args) throws Exception {
String xml = "<root><name type='type'>zhaipuhong</name><gender>male</gender><birthday><year>1970</year><month>12</month><day>17</day></birthday></root>";
String json = null;
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(xml);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
json = jsonObj.toString(2); //有缩进
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(json);
}
}
结果是:
{"root": {
"birthday": {
"month": 12,
"year": 1970,
"day": 17
},
"name": {
"content": "zhaipuhong",
"type": "type"
},
"gender": "male"
}}
这种虽然属性也可以转换出来,但是它却成了一个节点,我想要的是属性前面加一个“@”,即“@type”:"type"
请问有什么好的办法?
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
JSONObject简介
JAVA中使用JSON进行数据传递
JSON:Java--解析(读取)Json数据
JSON----json_lib.jar
json lib使用教程
JSON-lib框架,转换JSON、XML不再困难
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服