简体   繁体   中英

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. I have an ArrayList<Foo> that I want to store under the node labeled Foo . Gson outputs something like this:

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

I want the Json file to look like this:

{
    '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. 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. And instead of Jsonifying the entire ArrayList I could append each object individually. If I do this, how would I append it into the file (as opposed to the 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?

To get your desired output format, you could put your list in a Map with the key "foo."

    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'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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