我正在尝试使用 Newtonsoft 反序列化数组,以便我可以在列表框中显示来自基于云的服务器的文件,但无论我尝试什么,我总是会收到此错误:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: [. Path '[0].priv', line 4, position 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);
最佳答案
您的 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 字符串生成强类型类。
关于C# Newtonsoft反序列化JSON数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44011596/