所以这些是我的课程
public class Fencers{
private String name,nation;
private int id;
public Fencers(String name, String nation,int id) {
this.name = name;
this.nation = nation;
this.id = id;
}
}
以下类将其他类对象存储在数组列表中
import java.util.ArrayList;
public class FencersList {
private ArrayList<Fencers> collection;
public FencersList(){
collection = new ArrayList<Fencers>();
}
public ArrayList<Fencers> getCollection() {
return collection;
}
public void addfencer(Fencers fencer){
collection.add(fencer);
}
最后是主要的
import com.google.gson.Gson;
import java.io.*;
class Main{
public static void main(String[] args){
Fencers fencer1 = new Fencers("m","egy",100);
Fencers fencer2 = new Fencers("342","egy",120);
FencersList list = new FencersList();
list.addfencer(fencer1);
list.addfencer(fencer2);
Gson gson = new Gson();
try (PrintWriter out = new PrintWriter(new FileWriter("file.json"))) {
String jsonString = gson.toJson(list.getCollection());
out.write(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader br = new BufferedReader(new FileReader("file.json"));
Fencers[] fencers = gson.fromJson(br,Fencers[].class);
System.out.println(fencers);
list.addfencer(fencers);
} catch (Exception f){
f.printStackTrace();
}
}
}
在这里我设法将
FencersList
类对象保存在file.json
一切正常
我这里唯一的问题是我不能将数据转换回FencersList
只是因为这种格式使得Fencers
是一个数组并且FencerList
只接受来自Fencers
的普通类对象并且当我修复它并且让它正常它给了我一个错误Expected BEGIN_OBJECT but was BEGIN_ARRAY
所以我有点卡住了。
这是
file.json
顺便说一句
[
{
"name":"m",
"nation":"egy",
"id":100}
,{
"name":"342",
"nation":"egy",
"id":120
}
]
这里的错误是,当您将集合保存到 json 文件时,却试图将集合读取为 FencersList 对象。
我说的是这条线:
String jsonString = gson.toJson(list.getCollection());
这意味着如果你想将这个 jsonString 转换回目标对象类型应该与 list.getCollection() 的结果相同,即 List。但是您尝试将 json 字符串反序列化为 Fencers[],而不是这个。它不会工作
为了能够反序列化为 FencersList 你应该创建你的 json
String jsonString = gson.toJson(list);
这将使您的 json 看起来像这样(集合是您的 FencersList 类中的字段名称):
{ "collection":[{"name":"m", "nation":"egy", "id":100}] }