本文目录一览:
- 1、如何将xml的字符串转换为json
- 2、如何将XML文档转换为JSON格式
- 3、如何把xml转成json对象,底层代码
- 4、在java中怎么把xml文件转换成json格式
- 5、JAVA能把下面的 xml 转化为JSON
如何将xml的字符串转换为json
放上maven依赖
dependency
groupIdorg.json/groupId
artifactIdjson/artifactId
version20151123/version
/dependency
xml字符串转换为json字符串代码实现如下:
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
public class JsonUtils {
public static String xml2jsonString(String xml)throws JSONException{
JSONObject xmlJSONObj = XML.toJSONObject(xml);
return xmlJSONObj.toString();
}
}
json字符串转换为json对象代码实现如下:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
JSONObject jsonObject = null;
try{
jsonObject = JSON.parseObject(jsonString);
}catch(Exception e){
logger.error("json串转json对象时发生异常,json串="+jsonString);
throw new RuntimeException("json串转json对象时发生异常,json串="+jsonString,e);
}
return jsonObject;
不过org.json有个问题比较麻烦,xml如下所示:
?xml version="1.0" encoding="gb2312"?
payUnitinfo
err_msg/err_msg
retcode1/retcode
payUnits
payUnit
provinceIdv1955/provinceId
cityIdv1961/cityId
payProjectIdc2680/payProjectId
payUnitIdv96564/payUnitId
payUnitName浙江省电费/payUnitName
/payUnit
payUnit
provinceIdv1955/provinceId
cityIdv1961/cityId
payProjectIdc2680/payProjectId
payUnitIdv85002/payUnitId
payUnitName国网浙江省电力公司/payUnitName
/payUnit
/payUnits
/payUnitinfo
当xml中出现多个payUnit时,org.json将xml中的payUnit转换为json数组格式的字符串,当只有一个payUnit时,org.json将xml中的payUnit转换为json对象格式的字符串。
假设jsonObject是上述xml转换为json对象后的变量,则通过以下方式获取:
JSONObject payUnitsJsonObject = jsonObject.getJSONObject("payUnitinfo").getJSONObject("payUnits");
JSONObject payUnitJsonObject = null;
JSONArray payUnitJsonArray = null;
Object payUnitObject = payUnitsJsonObject.get("payUnit");
if(payUnitObject instanceof JSONObject){
payUnitJsonObject = (JSONObject)payUnitObject;
}else if(payUnitObject instanceof JSONArray){
payUnitJsonArray = (JSONArray)payUnitObject;
}
如何将XML文档转换为JSON格式
之所以使用JSON一般是为了跳过XML这个过程,使JAVA类型到客户端的javascript类型可以不需要再解析XML就直接生成.为什么会从XML转换成json?
个人建议是通过Java解析XML,生成JavaBean或者其它类型的java对象,然后使用GSON,将java对象转化成json.GSON是google开发的一个包,小巧而功能强大,可定制性也很强,推荐使用.
如何把xml转成json对象,底层代码
使用json-lib的XMLSerializer对象
(1)创建XMLSerializer对象
(2)使用XMLSerializer的read(xml)方法即可
[java] view plain copy
/* 第二种方法,使用json-lib提供的方法 */
//创建 XMLSerializer对象
XMLSerializer xmlSerializer = new XMLSerializer();
//将xml转为json(注:如果是元素的属性,会在json里的key前加一个@标识)
String result = xmlSerializer.read(xml).toString();
//输出json内容
System.out.println(result);
3.测试
[java] view plain copy
public class Test {
public static void main(String[] args) {
String xml = "class id="
+ "'1'"
+ "studentnameaaaaaa/nameage21/age/studentstudentnamebbbbbb/nameage22/age/student/class";
/* 第一种方法,使用JSON-JAVA提供的方法 */
//将xml转为json
JSONObject xmlJSONObj = XML.toJSONObject(xml);
//设置缩进
String jsonPrettyPrintString = xmlJSONObj.toString(4);
//输出格式化后的json
System.out.println(jsonPrettyPrintString);
/* 第二种方法,使用json-lib提供的方法 */
//创建 XMLSerializer对象
XMLSerializer xmlSerializer = new XMLSerializer();
//将xml转为json(注:如果是元素的属性,会在json里的key前加一个@标识)
String result = xmlSerializer.read(xml).toString();
//输出json内容
System.out.println(result);
}
第一种方法输出:
[java] view plain copy
{"class": {
"id": 1,
"student": [
{
"age": 21,
"name": "aaaaaa"
},
{
"age": 22,
"name": "bbbbbb"
}
]
}}
第二种方法输出:
[java] view plain copy
{"@id":"1","student":[{"name":"aaaaaa","age":"21"},{"name":"bbbbbb","age":"22"}]}
在java中怎么把xml文件转换成json格式
在java中把xml文件转换成json格式
1、前提需要jar包:
json-lib-2.4-jdk15.jar 和 xom-1.2.5.jar ,maven 仓库:
net.sf.json-lib
json-lib
2.4
jdk15
xom
xom
1.2.5
2、代码部分:
public static JSON xmlToJson(String xml) {
XMLSerializer xmlSerializer = new XMLSerializer();
if(xml!=null !”“.equals(xml)){
xml = xml.replaceAll(“\r|\n”, “”);
JSON json = xmlSerializer.read(xml);
return json;
}else{
return null;
}
}
public static void main(String[] args) {
String xmlStr = "parentid01/idnamemarry/name/parent";
JSON json = xmlToJson(xmlStr);
System.out.println(json.toString());
}
3、结果:
{“id”:”01”,”name”:”marry”}
JAVA能把下面的 xml 转化为JSON
ppackage com.shine.framework.core.util;/p
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
/**
* common xml conver utility
*
* @author viruscodecn@gmail.com
* @version Framework 2010.10.26
* @url
*/
public class XmlConverUtil {
/**
* map to xml xml nodekey label="key1"value1/keykey
* label="key2"value2/key....../node
*
* @param map
* @return
*/
public static String maptoXml(Map map) {
Document document = DocumentHelper.createDocument();
Element nodeElement = document.addElement("node");
for (Object obj : map.keySet()) {
Element keyElement = nodeElement.addElement("key");
keyElement.addAttribute("label", String.valueOf(obj));
keyElement.setText(String.valueOf(map.get(obj)));
}
return doc2String(document);
}
/**
* list to xml xml nodesnodekey label="key1"value1/keykey
* label="key2"value2/key....../nodenodekey
* label="key1"value1/keykey
* label="key2"value2/key....../node/nodes
*
* @param list
* @return
*/
public static String listtoXml(List list) throws Exception {
Document document = DocumentHelper.createDocument();
Element nodesElement = document.addElement("nodes");
int i = 0;
for (Object o : list) {
Element nodeElement = nodesElement.addElement("node");
if (o instanceof Map) {
for (Object obj : ((Map) o).keySet()) {
Element keyElement = nodeElement.addElement("key");
keyElement.addAttribute("label", String.valueOf(obj));
keyElement.setText(String.valueOf(((Map) o).get(obj)));
}
} else {
Element keyElement = nodeElement.addElement("key");
keyElement.addAttribute("label", String.valueOf(i));
keyElement.setText(String.valueOf(o));
}
i++;
}
return doc2String(document);
}
/**
* json to xml {"node":{"key":{"@label":"key1","#text":"value1"}}} conver
* onode class="object"key class="object"
* label="key1"value1/key/node/o
*
* @param json
* @return
*/
public static String jsontoXml(String json) {
try {
XMLSerializer serializer = new XMLSerializer();
JSON jsonObject = JSONSerializer.toJSON(json);
return serializer.write(jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* xml to map xml nodekey label="key1"value1/keykey
* label="key2"value2/key....../node
*
* @param xml
* @return
*/
public static Map xmltoMap(String xml) {
try {
Map map = new HashMap();
Document document = DocumentHelper.parseText(xml);
Element nodeElement = document.getRootElement();
List node = nodeElement.elements();
for (Iterator it = node.iterator(); it.hasNext();) {
Element elm = (Element) it.next();
map.put(elm.attributeValue("label"), elm.getText());
elm = null;
}
node = null;
nodeElement = null;
document = null;
return map;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* xml to list xml nodesnodekey label="key1"value1/keykey
* label="key2"value2/key....../nodenodekey
* label="key1"value1/keykey
* label="key2"value2/key....../node/nodes
*
* @param xml
* @return
*/
public static List xmltoList(String xml) {
try {
ListMap list = new ArrayListMap();
Document document = DocumentHelper.parseText(xml);
Element nodesElement = document.getRootElement();
List nodes = nodesElement.elements();
for (Iterator its = nodes.iterator(); its.hasNext();) {
Element nodeElement = (Element) its.next();
Map map = xmltoMap(nodeElement.asXML());
list.add(map);
map = null;
}
nodes = null;
nodesElement = null;
document = null;
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* xml to json nodekey label="key1"value1/key/node 转化为
* {"key":{"@label":"key1","#text":"value1"}}
*
* @param xml
* @return
*/
public static String xmltoJson(String xml) {
XMLSerializer xmlSerializer = new XMLSerializer();
return xmlSerializer.read(xml).toString();
}
/**
*
* @param document
* @return
*/
public static String doc2String(Document document) {
String s = "";
try {
// 使用输出流来进行转化
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 使用UTF-8编码
OutputFormat format = new OutputFormat(" ", true, "UTF-8");
XMLWriter writer = new XMLWriter(out, format);
writer.write(document);
s = out.toString("UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
return s;
}
}需要的jar
需要json-lib-2.1-jdk15.jar和xom-1.2.5.jar,maven pom.xml如下: