本文将介绍使用Java解析json和生成json,解析xml以及生成xml的一些方法。
前提摘要:JSON和XML 必须知道的传输格式.
JSON是什么?
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。
- 对象示例
{
"firstName":"Brett",
"lastName":"McLaughlin",
"email":"aaaa"
}
{
"people":[
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
{"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
{"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
]
}
映射的对象
源码在[^1]菜鸟笔记Github。
public class UserModel {
private String firstName;
private String lastName;
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
使用[^2]fastjosn解析String
/**
* java-object as json-string
*
* @param object
* @return
*/
public String seriazileAsString(Object object) {
if (object == null) {
return "";
}
try {
return JSON.toJSONString(object, features);
} catch (Exception ex) {
throw new SerializationException("Could not write JSON: "
+ ex.getMessage(), ex);
}
}
Object to String
/**
* json-string to java-object
*
* @param jsonString
* @return
*/
public T deserializeAsObject(String jsonString, Type clazz) {
if (jsonString == null || clazz == null) {
return null;
}
try {
return JSON.parseObject(jsonString, clazz);
} catch (Exception ex) {
throw new SerializationException("Could not write JSON: "
+ ex.getMessage(), ex);
}
}
执行测试
mvn test -Dtest=JsonUtilTest#testJsonObject
XML[^3]是什么?
可扩展标记语言(英语:Extensible Markup Language,简称:XML),是一种标记语言。标记指计算机所能理解的信息符号,通过此种标记,计算机之间可以处理包含各种信息的文章等。如何定义这些标记,既可以选择国际通用的标记语言,比如HTML,也可以使用像XML这样由相关人士自由决定的标记语言,这就是语言的可扩展性。XML是从标准通用标记语言(SGML)中简化修改出来的。它主要用到的有可扩展标记语言、可扩展样式语言(XSL)、XBRL和XPath等。
Tip:xml使用非常广,数据传输(API),数据存储(Evernote导出格式),配置文件(Spring Application.xml)。
JAXB实现 对象的序列化和反序列化
映射的对象 XmlUserModel
@XmlRootElement
public class XmlUserModel {
private int id;
private String firstName;
private String lastName;
private String email;
public String getEmail() {
return email;
}
@XmlElement
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
@XmlElement
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
@XmlElement
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Object to String
public static String seriazileAsString(Object object, Class clazz) {
if (object == null) {
return "";
}
try {
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
java.io.StringWriter sw = new StringWriter();
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(object, sw);
return sw.toString();
} catch (JAXBException ex) {
ex.printStackTrace();
}
return null;
}
从XML str 解析 Object
public static T deserializeAsObject(String xmlString, Class clazz) {
if (xmlString == null || clazz == null) {
return null;
}
JAXBContext jaxbContext = null;
try {
jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(xmlString);
T userModel = (T) jaxbUnmarshaller.unmarshal(reader);
return userModel;
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
执行测试XmlUtilTest
mvn test -Dtest=XmlUtilTest#testXmlObject
@Test
public void testXmlObject() {
XmlUserModel xmlUserModel = new XmlUserModel();
xmlUserModel.setFirstName("chen");
xmlUserModel.setLastName("billy");
xmlUserModel.setEmail("[email protected]");
xmlUserModel.setId(1);
String xmlStr = XmlUtil.seriazileAsString(xmlUserModel, XmlUserModel.class);
System.out.println(xmlStr);
//jsonStr -> object
XmlUserModel deXmlUserModel = XmlUtil.deserializeAsObject(xmlStr, XmlUserModel.class);
assertEquals(xmlUserModel.getId(), deXmlUserModel.getId());
}
生成的xml的Str如下:
[email protected]
chen
billy
更多Xml解析阅读推荐
- Java XML Tutorial
参考列表
- [^1]菜鸟笔记源码
- Jackson
- Jackson 2 – Convert Java Object to / from JSON
- [^2]fastjson
- Gson
- [^3]XML WIKI
- Java XML Tutorial
- JAXB
- SAX
- dom4j
本文源代码地址:https://github.com/daimaniu/cainiaobiji ,欢迎star 和 fork。
下期预告
下期预告(9月19号):Java常见的加密编码学习。
欢迎大家关注我,周更两篇Java技术文章。菜鸟笔记 下周一不见不散