Reputation: 115
I am trying to get file with a list of users in JSON, de-serialize it into a list of user type objects, add a new user to that list and then re-serialize that list and write it to the file.
Here is the code I used.
public async void appendFile(User _user)
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.GetFileAsync("LocalUsers.txt");
string Json = await FileIO.ReadTextAsync(file);
List<User> users = JsonConvert.DeserializeObject<List<User>>(Json);
users.Add(_user);
string s = convertJson(users);
await FileIO.WriteTextAsync(file, s);
}
When the code is run it throws this error: An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Xymby.Models.User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Not sure what I'm doing wrong here, any help would be appreciated also I would be open to any changes that are more efficient than my implementation.
Upvotes: 0
Views: 1173
Reputation: 9704
Your json is a single entity of the User type, so it will not deserialize into a list. Wrap the json with [ ]'s and it will work. Make sure that when you write the json file in the future that you are only writing a collection type and not an individual user.
Given what you've supplied as the current json file, the following should do:
[{"ID":"d5d8fa11-1a95-4a73-9666-66671bc03d51","Name":"Brian"}]
Upvotes: 0