第一种:
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"
请问有什么好的办法?
联系客服