日期:2014-05-20 浏览次数:20846 次
import java.io.InputStream;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.JSONTypes;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
public class ConvertJSONtoXMLSetRoot {
public static void main(String[] args) throws Exception {
InputStream is =
ConvertJSONtoXMLNoHints.class.getResourceAsStream("sample-json.txt");
String jsonData = IOUtils.toString(is);
XMLSerializer serializer = new XMLSerializer();
JSON json = JSONSerializer.toJSON( jsonData );
serializer.setRootName("SampleJSON"); //设置xml根元素为SampleJSON
serializer.setTypeHintsEnabled(false); //在元素属性上不显示原json的类型
String xml = serializer.write( json );
System.out.println(xml);
}
}
------解决方案--------------------
1.下载http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/
和它的依赖http://json-lib.sourceforge.net/
2.使用如:
JSONObject json = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");
String xml = XMLSerializer.write( json );
结果为:<o class="object">
<name type="string">json</name>
<bool type="boolean">true</bool>
<int type="number">1</int>
</o>
O(∩_∩)O~,你懂得