Reputation: 345
I am using Gson to write to and read from a file.
each time a user is created, I append a line which shows Username and ID.
I do this with the following (UserAccount being my pojo class, br is my buffered reader)::
UserAccount accountObj = new UserAccount();
FileWriter writer = new FileWriter("store.json", true);
accountObj.setUser(NewUserMethod());
accountObj.setID(NewIDMethod());
String json = gson.toJson(accountObj);
writer.write(json);
writer.close();
This makes the json file, which works - like this ::
{"USER":"noob123","ID":"99"}
When a new user does it, It will append the next line like so ::
{"USER":"noob123","ID":99}{"USER":"pro321","ID":100}
When I attempt to read this json file, I got the following error ::
"use JsonReader.setLenient(true) to accept malformed JSON at line 1, column 36"
So I understand it may be incorrect format and may need something like ::
{"ACCOUNT":{"USER":"noob123","ID":99},"ACCOUNT":{"USER":"pro321","ID":100}}
I have spent some time trying to create JSON in this format, or at least reference to the correct USER key when the matching USER name is used. Any help is greatly appreciated.
Thanks
Upvotes: 0
Views: 462
Reputation: 8368
You should use JSONArray to save this information into file. Then you can read content of file into list of UserAccount
, add new object into this list.
Then you should override content of file.
E.g. :
UserAccount accountObj = new UserAccount();
accountObj.setUser(NewUserMethod());
accountObj.setID(NewIDMethod());
List<UserAccount> userAccounts = gson.fromJson(<jsonContent>, new TypeToken<List<UserAccount>>() {
}.getType());
userAccounts.add(accountObj);
String json = gson.toJson(userAccounts);
writer.write(json);
writer.close();
Upvotes: 1