首页 文章

C#Newtonsoft反序列化JSON数组

提问于
浏览
3

我正在尝试使用Newtonsoft对数组进行反序列化,因此我可以在列表框中显示来自基于 Cloud 的服务器的文件,但无论我尝试什么,我总是会收到此错误:

Newtonsoft.Json.JsonReaderException:'解析值时遇到意外的字符:[ . 路径'[0] .priv',第4行,第15位 . '

这是一个尝试反序列化的示例:

[
 {
  "code": 200,
  "priv": [
     {
        "file": "file.txt",
        "ext": "txt",
        "size": "104.86"
     },
     {
        "file": "file2.exe",
        "ext": "exe",
        "size": "173.74"
     },

  ],
  "pub": [
     {
        "file": "file.txt",
        "ext": "txt",
        "size": "104.86"
     },
     {
        "file": "file2.exe",
        "ext": "exe",
        "size": "173.74"
     }
  ]
 }
]

我尝试使用像这样的C#类:

public class ListJson
{
    [JsonProperty("pub")]
    public List List { get; set; }
}

public class List
{
    [JsonProperty("file")]
    public string File { get; set; }

    [JsonProperty("ext")]
    public string Ext { get; set; }

    [JsonProperty("size")]
    public string Size { get; set; }
}
    [JsonProperty("priv")]
public List List { get; set; }
}

public class List
{
    [JsonProperty("file")]
    public string File { get; set; }

    [JsonProperty("ext")]
    public string Ext { get; set; }

    [JsonProperty("size")]
    public string Size { get; set; }
}

并反序列化:

List<list> fetch = Newtonsoft.Json.JsonConvert.DeserializeObject<List<list>>(json);

2 回答

  • 7

    JSON的正确C#类结构如下:

    public class FileEntry
    {
        public string file { get; set; }
        public string ext { get; set; }
        public string size { get; set; }
    }
    
    public class FileList
    {
        public int code { get; set; }
        public List<FileEntry> priv { get; set; }
        public List<FileEntry> pub { get; set; }
    }
    

    以这种方式反序列化:

    var fetch = JsonConvert.DeserializeObject<FileList[]>(json);
    var fileList = fetch.First(); // here we have a single FileList object
    

    如在另一个答案中所述,创建一个名为 List 的类不会自动将其转换为对象集合 . 您需要从数组中声明要反序列化的类型集合类型(例如 List<T>T[] 等) .

    小提示:如有疑问,请使用json2csharp.com从json字符串生成强类型类 .

  • 0

    目前 List 有一个名为 privList 实例,尽管名称为:但不会使其成为列表 . 要反序列化JSON数组( "priv": [...] ),它需要一个数组或类似列表的类型,例如某些 TList<T> . 大概是 List<FileThing> ,如果我们假设 FileThing 实际上是第二种类型叫做 List (你有2) .

相关问题