问题描述
我正在尝试使用Newtonsoft反序列化数组,以便可以在列表框中显示来自基于云的服务器的文件,但是无论我尝试什么,我总是最终会收到此错误:
I'm trying to deserialize an array using Newtonsoft so i can display files from a cloud based server in a listbox but i always end up getting this error no matter what i try:
这是尝试反序列化的示例:
Thisis an example try to deserialize:
[
{
"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#类:
I tried using a C# Class like this:
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);
推荐答案
JSON的正确C#类结构如下:
The correct C# class structure for your JSON is the following:
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[]
等).
As said in the other answer, creating a class called List
doesn't automagically turn it into a collection of objects. You need to declare the types to be deserialized from an array a collection type (e.g. List<T>
, T[]
, etc.).
小技巧:如有疑问,请使用 json2csharp.com 从json字符串生成强类型类
Small tip: when in doubt, use json2csharp.com to generate strongly typed classes from a json string.
这篇关于C#Newtonsoft反序列化JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!