如何把一个对象进行永久的保存?
【用有规律的字符串代表一个对象】
如想保存 Student stu = new Student(1, "张飞", 19, 178.5);
这样的学生对象
可以用
1,张飞,19,178.5
保存
【序列化】
1. 概念:把一个对象的状态信息转化成可以保存或者传输的形式的过程
2. 序列化: 对象转化成二进制
反序列化:二进制转化成对象
3. 注意点:
a. 要序列化的对象必须实现 Serializable 接口
b. 这个对象依赖的类型全部都要实现 Serializable 接口
【XML】
Extensible Markup Language
1. 可扩展标记语言
2. 作用: 将数据转化成XML后,可以真正实现数据的跨平台共享
不同的语言中,解析XML的方式都是一致的
3. 语法规则: <a>
1) 所有元素必有关闭标签 <a /> <a></a>
2) 大小写敏感 <a> <A> 是不同的标记
3) 必须正确的嵌套
<a><b></a></b> 是错误的
4) 必须有根元素
<root>
<a></a>
<b></b>
</root>
5) 属性值必须加引号
<student id="1" />
6) 空格会被保留
7)CDATA
术语 CDATA 指的是不应由 XML 解析器进行解析的文本数据(Unparsed Character Data)。
CDATA 部分中的所有内容都会被解析器忽略。
CDATA 部分由 "<![CDATA[" 开始,由 "]]>" 结束
4. 举例
xml格式文件
<?xml version="1.0" encoding="utf-8"?>
<stulist>
<student id="1">
<name>张飞</name>
<age>19</age>
<height>178.5</height>
</student>
<student id="2">
<name>关羽</name>
<age>20</age>
<height>200.1</height>
</student>
<student id="3">
<name>刘备</name>
<age>21</age>
<height>160.9</height>
</student>
<student id="4">
<name>黄忠</name>
<age>59</age>
<height>175.3</height>
</student>
<student id="5">
<name>赵云</name>
<age>17</age>
<height>180.1</height>
</student>
</stulist>
5. XML 解析
1) DOM解析
将XML文档内容一次性读入内存
然后对文档进行树形建模分析节点信息
一步步读取到最后文本类型节点内容
优点: 可以进行随机读取
缺点: 占用内存较大
package com.bwf.xml;
import java.beans.FeatureDescriptor;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.bwf.bean.Student;
public class Demo2 {
public static void main(String[] args) {
List<Student> list = parse();
for (Student student : list) {
System.out.println(student);
}
}
/**
* DOM解析 parse <-> format
*
* DocumentBuilderFactory -> DocumentBuilder -> Document
* 文档对象 Document -> 根元素节点 -> 所有的子元素 -> 子元素 -> ... -> Text类型节点
*
* @return
*/
public static List<Student> parse(){
List<Student> list = new ArrayList<>();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// 文档对象 Document
Document document = db.parse(new File("stu.xml"));
// 根元素节点
Element root = document.getDocumentElement();
// 所有的子元素
NodeList nodeList = root.getChildNodes();
for(int i = 0; i < nodeList.getLength(); i ++) {
Student s = new Student();
// 子元素 student节点
Node stuNode = nodeList.item(i);
s.setId(Integer.parseInt(stuNode.getAttributes().item(0).getNodeValue()));
// 拿出所有的子节点 - 属性
NodeList fieldlist = stuNode.getChildNodes();
for(int j = 0; j < fieldlist.getLength(); j ++) {
// 子元素节点 name age height
Node fieldNode = fieldlist.item(j);
switch (fieldNode.getNodeName()) {
case "name":
s.setName(fieldNode.getTextContent());
break;
case "age":
s.setAge(Integer.parseInt(fieldNode.getTextContent()));
break;
case "height":
s.setHeight(Double.parseDouble(fieldNode.getTextContent()));
break;
default:
break;
}
}
list.add(s);
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
}
2) SAX解析
用事件流的方式进行解析
优点: 占内存小
缺点: 不能随机读取, 只读只进
package com.bwf.xml;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.bwf.bean.Student;
public class Demo3 {
public static void main(String[] args) {
parse();
}
/**
* SAX解析
* 用事件流的方式一点点分析
*/
public static List<Student> parse(){
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
parser.parse(new FileInputStream("stu.xml"), new MyHandler());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
static class MyHandler extends DefaultHandler{
@Override
public void startDocument() throws SAXException {
System.out.println("startDocument");
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
System.out.println("startElement" + " qName = " + qName + " attributes = " + attributes.getValue(0));
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
System.out.println("characters " + new String(ch, start, length));
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("endElement qName = " + qName);
}
@Override
public void endDocument() throws SAXException {
System.out.println("endDocument");
}
}
}
【json】
1. 一种轻量级数据交换格式
2. 语法:
: 表示一对键值对
, 分割键值对
{} 表示一个对象
[] 表示一个数组
3. 举例
new Student(1, "张飞", 19, 178.5)
[{"id":"1", "name":"张飞", "age":"19", "height":"178.5"},
{"id":"1", "name":"张飞", "age":"19", "height":"178.5"},
{"id":"1", "name":"张飞", "age":"19", "height":"178.5"}]
4. www.json.org
json格式文件解析的jar包有多种,首推google的gson
package com.bwf.json;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import com.bwf.bean.Student;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Demo1 {
public static void main(String[] args) throws IOException {
//gson读出
// Student s1 = new Student(1, "张飞", 19, 178.5);
// // 转成json字符串
// String json = new Gson().toJson(s1);
// System.out.println(json);
// List<Student> list = new ArrayList<>();
// list.add(new Student(1, "张飞", 19, 178.5));
// list.add(new Student(2, "关羽", 20, 200.1));
// list.add(new Student(3, "刘备", 21, 160.9));
// list.add(new Student(4, "黄忠", 59, 175.3));
// list.add(new Student(5, "赵云", 17, 180.1));
//
//
// String json = new Gson().toJson(list);
// System.out.println(json);
// writeToFile(json);
//gson写入
List<Student> list = parse();
for (Student student : list) {
System.out.println(student);
}
}
public static List<Student> parse() throws FileNotFoundException{
List<Student> list = new ArrayList<>();
// 获得json的解析器
JsonParser parser = new JsonParser();
// 获得文件的输入流
Reader r = new FileReader("stu.json");
// 分清是数组还是对象
JsonArray array = (JsonArray) parser.parse(r);
for(int i = 0; i < array.size(); i ++) {
// 获得数组中的每一个元素(注意 是数组还是对象)
JsonObject object = (JsonObject) array.get(i);
Student stu = new Student();
stu.setId(object.get("id").getAsInt());
stu.setName(object.get("name").getAsString());
stu.setHeight(object.get("height").getAsDouble());
stu.setAge(object.get("age").getAsInt());
list.add(stu);
}
return list;
}
private static void writeToFile(String s) throws IOException {
Writer w = new FileWriter("stu.json");
w.write(s);
w.flush();
w.close();
}
}
5. json 和 XML的比较
json对于XML来说,数据体积较小
json对于数据的描述性比XML较低
json的速度远远高于XML
json与js无缝交互
解析手段同样丰富