简体   繁体   English

Android将JSON文件读/写到内部存储

[英]Android Read/Write JSON file to Internal Storage

I'm trying to use Gson to serialize my Java classes and store them in a .json file. 我正在尝试使用Gson序列化我的Java类并将它们存储在.json文件中。 I have an ArrayList<Foo> that I want to store under the node labeled Foo . 我有一个ArrayList<Foo> ,我想存储在标记为Foo的节点下。 Gson outputs something like this: Gson输出如下内容:

[{'id':1},{'id':2},{'id':3}]

I want the Json file to look like this: 我希望Json文件看起来像这样:

{
    'Foo': [{'id':1},{'id':2},{'id':3}],
    'bar': ...
}

I've tried using the JsonWriter class, but I believe this is for external storage since I am getting a ReadOnly error. 我尝试使用JsonWriter类,但是由于遇到ReadOnly错误,因此我相信这是用于外部存储的。 This is how I'm trying to write it: 这就是我试图写的方式:

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(gson.toJson(foos).getBytes()); // foos is ArrayList<Foo>
fos.close();

I'm thinking I need to store it in a JsonObject instead of writing it directly to a file. 我在想我需要将其存储在JsonObject中,而不是直接将其写入文件中。 And instead of Jsonifying the entire ArrayList I could append each object individually. 而不是合理化整个ArrayList,我可以分别附加每个对象。 If I do this, how would I append it into the file (as opposed to the JsonObject)? 如果执行此操作,如何将其附加到文件中(与JsonObject相对)?

The main issue I'm facing is actually reading from the file. 我面临的主要问题实际上是从文件中读取。 How do I go about reading the entire Json file into a JsonObject? 如何将整个Json文件读入JsonObject?

To get your desired output format, you could put your list in a Map with the key "foo." 为了获得所需的输出格式,您可以将列表放在键为“ foo”的Map中。

    Map<String, List<Foo>> map = new HashMap<>();
    map.put("Foo", foos);
    String output = gson.toJson(map);

Then you should get this output 那你应该得到这个输出

{
    'Foo': [{'id':1},{'id':2},{'id':3}]
}

Obviously the main reason you would want to do something like this is if you were storing things other than a list called 'Foo'. 显然,您想要执行此类操作的主要原因是,如果您存储的内容不是名为“ Foo”的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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