如果您只是想以JSON格式序列化和反序列化对象状态,而又不太在乎JSON的确切形状,则XStream使得此操作非常容易。它可以容忍几乎任何Java对象结构,而且不如Gson那样固定。
最初设计为序列化为XML,但是如果使用JettisonMappedXmlDriver
,它将输出JSON。我发现它是一个编写良好且可靠的库。
Product product = new Product("Banana","123",23.00);
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("product",Product.class);
System.out.println(xstream.toXML(product));
产生:
{“ product”:{“ name”:“ Banana”,“ id”:123,“ price”:23.0}}
要重新阅读:
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias("product",Product.class);
Product product = (Product) xstream.fromXML(json);
System.out.println(product.getName());
打印:
香蕉
,
要写入文件:
Gson gson = new Gson();
try (FileWriter writer = new FileWriter(file)) {
gson.toJson(board,writer);
} catch (IOException e) {
e.printStackTrace();
}
要读取文件:
Gson gson = new Gson();
try (Reader reader = new FileReader(file)) {
Board board = gson.fromJson(reader,Board.class);
System.out.println(board);
} catch (IOException e) {
e.printStackTrace();
}
注意:我的假设是
-
board
是Board
类的对象
- 您已在
toString()
中适当地覆盖了Board
方法,以便System.out.println(board);
将显示board
的详细信息。
本文链接:https://www.f2er.com/3007247.html