XML和JSON的解析
一、DOM4J解析XML案例
1.解析本地文件案例
解析之前需要引入jar文件 dom4j.jar
//1. 获取输入流
FileInputStream fis = new FileInputStream("Demo1.xml");
//2. 创建XML读取对象
SAXReader sr = new SAXReader();
//3. 读取并得到文档对象
Document doc = sr.read(fis);
//4. 通过文档获取根元素
Element root = doc.getRootElement();
//5. 开始解析元素
List<Element> es = root.elements();
Element book = es.get(1);
System.out.println(book.attributeValue("id"));
fis.close();
2.解析网络文件案例
String phone = "12345678987";
//1. 获取到XML资源的输入流
URL url = new URL("http://apis.juhe.cn/mobile/get?phone="+phone+"&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
//2. 创建一个XML读取对象
SAXReader sr = new SAXReader();
//3. 通过读取对象 读取XML数据,并返回文档对象
Document doc = sr.read(is);
//4. 获取根节点
Element root = doc.getRootElement();
//5. 解析内容
String code = root.elementText("resultcode");
3.DOM4J - XPATH解析XML
路径表达式:
1. / : 从根节点开始查找
2. // : 从发起查找的节点位置 查找后代节点 ***
3. . : 查找当前节点
4. .. : 查找父节点
5. @ : 选择属性. *
属性使用方式:
[@属性名='值']
[@属性名>'值']
[@属性名<'值']
[@属性名!='值']
XPATH解析本地文件案例:
//1. 获取输入流
FileInputStream fis = new FileInputStream("Demo1.xml");
//2. 创建XML读取对象
SAXReader sr = new SAXReader();
//3. 读取并得到文档对象
Document doc = sr.read(fis);
//4. 通过文档对象+xpath,查找所有的name节点
List<Node> names = doc.selectNodes("//book[@id='1001']//name");
for (int i=0;i<names.size();i++){
System.out.println(names.get(i).getName());
System.out.println(names.get(i).getText());
}
fis.close();
二、两种解析JSON的jar包
1.GSON
1.将对象转换为JSON字符串
//String json = new Gson().toJSON(要转换的对象);
Book b = new Book();
String json = new Gson().toJson(b);
System.out.println(json);
2.将JSON字符串转换为对象
//对象 = new Gson().fromJson(JSON字符串,对象类型.class);
String json = "{\"id\":1,\"name\":\"金苹果\",\"info\":\"种金苹果\"}";
Book book = new Gson().fromJson(json, Book.class);
System.out.println(book.toString());
2.FastJson
1..将对象转换为JSON字符串
//String json=JSON.toJSONString(要转换的对象);
Book b = new Book();
String json=JSON.toJSONString(b);
System.out.println(json);
2.将JSON字符串转换为对象
//类型 对象名=JSON.parseObject(JSON字符串, 类型.class);
//或
//List<类型> list=JSON.parseArray(JSON字符串,类型.class);
String json = "{\"id\":1,\"name\":\"金苹果\",\"info\":\"种金苹果\"}";
Book book = JSON.parseObject(json, Book.class);
System.out.println(book.toString());