C# Newtonsoft反序列化JSON数组

标签 c# json serialization json.net deserialization

我正在尝试使用 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/

相关文章:

json - 在 Mac 上使用 Safari 通过 HTTP 发送 POST 请求

java - 将 java.util.Date 转换为 json 格式

php - 测试变量是否可序列化

c# - 在 VisualStudio 调试器退出时执行代码

c# - 在 C 结构中设置变量就像在 C# 类构造函数中一样

c# - iOS、Android、Windows 10 移动模拟器是否可用于使用 Visual Studio 2015 开发 Xamarin.Forms?

c# - 在某些条件下序列化时忽略属性

c# - 试图制作一个计算三角形面积的程序,我想将它与 Math.Round 一起使用,但不知道将其正确放置在哪里

java - python 和 java 应用程序可以使用哪些数据交换格式相互通信?

json - 基于 Spring 安全角色的 Jackson @JsonIgnore 字段