简体   繁体   English

使用Gson将对象数组写入文件

[英]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: 您不必按每个元素序列化给定的输入数组:

  • Gson can do it all itself; Gson可以做到这一切;
  • your method assumes the input array is exactly 10 elements long (thus, throwing ArrayIndexOutOfBoundsException if the input array has less elements, or writing only first 10 elements); 你的方法假定输入数组正好是10个元素长(因此,如果输入数组中元素较少,或者只写入前10个元素,则抛出ArrayIndexOutOfBoundsException );
  • your method does not write well-formed JSON: {},{},{} is invalid, whilst [{},{},{}] is; 你的方法不能写出格式正确的JSON: {},{},{}无效,而[{},{},{}]是;
  • your method, as suggested by RealSkeptic , does not need intermediate string representations. 您的方法,如RealSkeptic建议 ,不需要中间字符串表示。

All you need are just two methods Gson.toJson and Gson.fromJson . 你只需要两个方法Gson.toJsonGson.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM