第一,xml转json
需要用到jar是org.json-2.0.jar
下载链接:
org.json-2.0.jar
接下来是转换代码:
public static void main(String[] args) throws JSONException {
//String xml = "<test>dddd</test>";//xml
String xml = "<?xml version=\"1.0\" encoding=\"GBK\" ?> "
+ "<test>dddd</test>";//xml
org.json.JSONObject xmlJSONObj = XML.toJSONObject(xml);//转化
System.out.println(xmlJSONObj.toString());//查看结果
}
输出结果是:
{"test":"dddd"}
补充
######json字符串转json对象
JSONObject 是org.json包的
String head = "{\n" +
"\t\"head\": {\n" +
"\t\t\"respType\": \"E\",\n" +
"\t\t\"msgType\": 2,\n" +
"\t\t\"reqDate\": 20180815150916,\n" +
"\t}\n" +
"}";
//head为json字符串
JSONObject head = new JSONObject(head);
//获取json节点的内容只能一级一级获取
String reqDate = head.getString("reqDate");
//补充2 --2018.10.29
//新的获取方式
/* <head>
<version>1.0.0</version>
<agencyId>549440172770016</agencyId>
<msgType>02</msgType>
<tranCode>IFP001</tranCode>
<reqMsgId>2018102911013600</reqMsgId>
<payMsgId>201810291101386518</payMsgId>
<reqDate>20181029110136</reqDate>
<respDate>20181029110138</respDate>
<respType>S</respType>
<respCode>000000</respCode>
<respMsg>绑卡成功</respMsg>
</head>
<body>
<bankCardNo><![CDATA[6231132201000367979]]></bankCardNo>
<userId><![CDATA[1540782096581]]></userId>
<bindId><![CDATA[1540782098182tYBX]]></bindId>
<bankCode><![CDATA[313]]></bankCode>
</body>
</merchant>*/
// bindCardData 赋值上面的内容
JSONObject xmlJSONObj = XML.toJSONObject(bindCardData);//转化
// String head = new JSONObject(xmlJSONObj.getString("merchant")).getString("head");
//JSONObject xmlJSONObjHead = new JSONObject(head);
//改成对象获取的方式 --2018.10.29
JSONObject xmlJSONObjHead = (JSONObject)(xmlJSONObj.getJSONObject("merchant")).get("head");
String respType = xmlJSONObjHead.getString("respType");
第二,json转xm
l
需要用到的jar包
代码:
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
/**
* 2018.02.05
* @author tlimited
*
*/
public class Json2XML {
public static void main(String[] args) throws DocumentException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "test");
jsonObject.put("age", "28");
System.out.println(json2Xml(jsonObject, "root"));
}
public static String json2Xml(JSONObject json, String rootName) throws DocumentException {
String xml = "";
XMLSerializer xmlSerializer = new XMLSerializer();
xmlSerializer.setTypeHintsEnabled(false);
xmlSerializer.setRootName(rootName);
String sContent = xmlSerializer.write(json);
try {
Document docCon = DocumentHelper.parseText(sContent);
xml = docCon.getRootElement().asXML();
} catch (DocumentException e) {
e.printStackTrace();
}
return xml;
}
/**
* 这个方法不知道是不是有bug,读取时候会把头弄没了,
* @param json
* @return
* @throws DocumentException
*/
public static String xml2Json(String json) throws DocumentException {
String sXml = "";
XMLSerializer xmlSerializer = new XMLSerializer();
String sContent = xmlSerializer.read(json).toString();
System.out.println(sContent);
return null;
}
}
下面是xml与bean互相转化的工具类
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
* <p>xml与bean相互转化工具类:</p>
* <p></p>
* @author tlimited
*/
public class xmlOrBeanBUtils {
/**
* JavaBean转换成xml
* 默认编码UTF-8
* @param obj bean对象
* @param writer
* @return
* @throws EMPException
*/
public static String convertToXml(Object obj) throws Exception {
return convertToXml(obj, "UTF-8");
}
/**
* JavaBean转换成xml
* @param obj bean对象
* @param encoding 编码设置
* @return
* @throws EMPException
*/
public static String convertToXml(Object obj, String encoding) throws Exception {
String result = null;
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
//Marshaller.JAXB_FORMATTED_OUTPUT 决定是否在转换成xml时同时进行格式化(即按标签自动换行,否则即是一行的xml)
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//Marshaller.JAXB_ENCODING xml的编码方式
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
result = writer.toString();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("JavaBean转换成xml失败:"+e.getMessage());
}
return result;
}
/**
* xml转换成JavaBean
* @param xml
* @param c
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T converyToJavaBean(String xml, Class<T> c) {
T t = null;
try {
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
t = (T) unmarshaller.unmarshal(new StringReader(xml));
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
}
下面是json与bean互相转化
用的是阿里巴巴的Json包,我用的是fastJson-1.2.17.jar,这个版本
下载链接
bean代码:
/**
* bean
* @author tlimted
*
*/
public class User {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
测试转化代码:
import com.alibaba.fastjson.JSON;
public class Test {
public static void main(String[] args) {
//********json转bean***********//
String json = "{'name':'tww','age':'12'}";
User user = JSON.parseObject(json,User.class);
System.out.println(user.toString());
//******bean转json*****//
User user2 = new User();//创建对象
user2.setName("res");//对象赋值
user2.setAge("41");
Object json2 = JSON.toJSON(user2);//转化
System.out.println(json2.toString());
}
}
输出结果:
json转bean
User [name=tww, age=12]
输出bean转json
{"name":"res","age":"41"}