Десериализация JSON в c# - что не так? - PullRequest
0 голосов
/ 17 марта 2020

Я безуспешно пытаюсь десериализовать этот JSON в c#:

{
    "settings": {
        "path": "http:\/\/www.igormasin.it\/fileuploads\/tanja_23a6id"
    },
    "files": [{
        "file": "\/IMG_0992-Edit_a.jpg"
    }, {
        "file": "\/IMG_1024-Edit_a.jpg"
    }, {
        "file": "\/IMG_1074-Edit_a.jpg"
    }, {
        "file": "\/Untitled-1.jpg"
    }]
}

мой код:

public class JsonTxt
{
    public IList<string> settings { get; set; }
    public IList<string> files { get; set; }
}

строка загрузки содержит текст Json:

 var deserialized = JsonConvert.DeserializeObject<JsonTxt>(downloadString);        
 Console.WriteLine("*************************************************");
 Console.WriteLine(deserialized.settings[0].ToString());
 Console.WriteLine(deserialized.files.Count);

исключение:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. 
{"name":"value"}) into type 'System.Collections.Generic.IList`1[System.String]' 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<T>) 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.
Path 'settings.path', line 1, position 20.'

Я не могу понять ошибку и то, что я должен сделать .. Из того, что я понимаю, IList не так, но что еще будет что правильно написать?

Ответы [ 2 ]

5 голосов
/ 17 марта 2020

Структура вашего класса должна выглядеть примерно так:

public class JsonTxt
{
    public Settings Settings { get; set; }
    public IList<File> Files { get; set; }
}

public class Settings
{
    public string Path { get; set; }
}

public class File
{
    public string File { get; set; }
}

Settings - это объект, а не коллекция, а Files - это коллекция объектов, а не строк.

2 голосов
/ 17 марта 2020

Тип вашего класса предполагает настройки IList:

public class JsonTxt
{
    public IList<string> settings { get; set; }
    public IList<string> files { get; set; }
}

, но в json вы предоставляете объект

 "settings": {
        "path": "http:\/\/www.igormasin.it\/fileuploads\/tanja_23a6id"
    },

, вам следует изменить тип атрибутов JsonText, чтобы он соответствовал вашему JSON

...