

js xml转json,json转xml
在线XML转JSON,JSON转XML-BeJSON.com
http://www.bejson.com/xml2json/
------------------------------------------------------------------------------代码
package xml2json;
import java.io.File;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
/**
* xml转json,json转xml
*
* @author happyqing
* @since 2016.8.8
*/
public class JsonUtil {
public static JSON xml2json(String xml) {
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read(xml);
// xmlSerializer.read(String arg0);
// xmlSerializer.readFromFile(File arg0);
// xmlSerializer.readFromFile(String path);
// xmlSerializer.readFromStream(InputStream arg0);
return json;
}
public static String json2xml(String json) {
JSONObject jobj = JSONObject.fromObject(json);
// JSON jsonObject = JSONSerializer.toJSON(json);
String xml = new XMLSerializer().write(jobj);
return xml;
}
public static Map json2map(String json) throws Exception{
ObjectMapper mapper = new ObjectMapper();
Map<String, String> jsonMap = mapper.readValue(json.toString(),new TypeReference<Map<String, Object>>() {});
return jsonMap;
}
public static void main(String[] args) throws Exception {
String text = FileUtils.readFileToString(new File("D:/workspace/workspace_3.7/xml2map/src/xml2json/sample.xml"),"UTF-8");
JSON json = xml2json(text);
System.out.println(json.toString(1)); // json.toString(1) 格式化输出
// String xml = json2xml(json.toString());
// System.out.println(xml);
}
}
本文介绍了一种在Java中实现XML与JSON互相转换的方法,包括使用XMLSerializer将XML转换为JSON,以及将JSON转换回XML的过程。同时,还提供了一个示例,展示了如何读取XML文件并将其转换为格式化的JSON输出。
&spm=1001.2101.3001.5002&articleId=106094606&d=1&t=3&u=3f3789dbba4c46d6a64aa12680f692e5)
1万+

被折叠的 条评论
为什么被折叠?



