[英]Writing array of objects to a file with Gson
public boolean wirteJson(Passenger passenger[]){
try {
file = new FileWriter(System.getProperty("user.dir")+"/"+fileName);
for (int i = 0; i < 10; i++) {
String json =gson.toJson(passenger[i]);
file.write(json);
}
file.flush();
file.close();
} catch (IOException ex) {
return false;
}
return false;
}
I'm trying to write the passenger
array to a file with Gson. 我正在尝试将passenger
阵列写入Gson的文件中。 I'm open to alternatives. 我愿意接受替代方案。
You don't have to serialize the given input array by each element: 您不必按每个元素序列化给定的输入数组:
ArrayIndexOutOfBoundsException
if the input array has less elements, or writing only first 10 elements); 你的方法假定输入数组正好是10个元素长(因此,如果输入数组中元素较少,或者只写入前10个元素,则抛出ArrayIndexOutOfBoundsException
); {},{},{}
is invalid, whilst [{},{},{}]
is; 你的方法不能写出格式正确的JSON: {},{},{}
无效,而[{},{},{}]
是; All you need are just two methods Gson.toJson and Gson.fromJson . 你只需要两个方法Gson.toJson和Gson.fromJson 。 So, here is a simple example: 所以,这是一个简单的例子:
final class Passenger {
final String name;
Passenger(final String name) {
this.name = name;
}
}
public static void main(final String... args)
throws IOException {
final File file = createTempFile("q43439637_", "_q43439637");
file.deleteOnExit();
try ( final FileWriter fileWriter = new FileWriter(file) ) {
final Passenger[] before = { new Passenger("Alice"), new Passenger("Bob") };
gson.toJson(before, fileWriter);
}
try ( final FileReader fileReader = new FileReader(file) ) {
final Passenger[] after = gson.fromJson(fileReader, Passenger[].class);
for ( final Passenger p : after ) {
System.out.println(p.name);
}
}
}
Output: 输出:
Alice 爱丽丝
Bob 短发
PS Your out-of- catch
return
seems to have to return true
rather than false
. PS你的失catch
return
似乎要回归true
而不是false
。 Also, flush()
is unnecessary before close()
. 另外,在close()
之前不需要flush()
close()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.