首页 > 解决方案 > 在 C# 中反序列化 JSON - 有什么问题?

问题描述

我试图在 c# 中反序列化这个 JSON,但没有成功:

{
    "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 是错误的,但还有什么是正确的写法?

标签: c#jsondeserialization

解决方案


你的类结构需要是这样的:

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是一个对象的集合而不是字符串。


推荐阅读