使用org.json库,可以很容易地将org.json转换为JSON.但是转换回XML总是将JSON属性转换为XML节点:
import org.json.JSONObject;
import org.json.XML;
public class Test {
public static void main(String[] args) throws Exception {
String xml = "<tag1 attr1=\"val1\"><tag2 attr2=\"val2\"/></tag1>";
System.out.println(xml);
JSONObject str = XML.toJSONObject(xml);
System.out.println(str);
JSONObject json = new JSONObject(str.toString());
String xml2 = XML.toString(json);
System.out.println(xml2);
}
}输出
<tag1 attr1="val1"><tag2 attr2="val2"/></tag1>
{"tag1":{"attr1":"val1","tag2":{"attr2":"val2"}}}
<tag1><attr1>val1</attr1><tag2><attr2>val2</attr2></tag2></tag1>如何检索我的XML属性?
发布于 2018-09-23 13:44:29
Underscore-java有静态方法U.xmlToJson(xml)和U.jsonToXml(json)。Live example
import com.github.underscore.lodash.U;
public class Test {
public static void main(String[] args) {
String xml = "<tag1 attr1=\"val1\"><tag2 attr2=\"val2\"/></tag1>";
System.out.println(U.xmlToJson(xml));
System.out.println(U.jsonToXml(U.xmlToJson(xml)));
}
}
// {
// "tag1": {
// "-attr1": "val1",
// "tag2": {
// "-attr2": "val2",
// "-self-closing": "true"
// }
// },
// "#omit-xml-declaration": "yes"
// }发布于 2016-06-24 05:54:41
如果您想在下面的XML中转换
<tag1><attr1>val1</attr1><tag2><attr2>val2</attr2></tag2></tag1> 您将得到相同的JSON结果;
{"tag1":{"attr1":"val1","tag2":{"attr2":"val2"}}}因此,从JSON转换回XML可能会导致歧义。因此,最好编写一些自定义代码,表明如果一个json字段和一个属性或标记。我不确定是否有用于转换的库,但此链接可能会有所帮助;
http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html
https://stackoverflow.com/questions/38002128
复制相似问题