简体   繁体   中英

C# JSON.net having trouble deserializing and reserializing object from file

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 (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[Xymby.Models.User]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg 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.

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"}]

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