【问题标题】:C# Newtonsoft deserialize JSON arrayC# Newtonsoft 反序列化 JSON 数组
【发布时间】:2017-10-16 03:12:27
【问题描述】:

我正在尝试使用 Newtonsoft 反序列化一个数组,以便我可以在列表框中显示来自基于云的服务器的文件,但无论我尝试什么,我最终都会收到此错误:

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);

【问题讨论】:

  • 你用它来验证你的JSON 提示它有语法错误
  • 你有 2 个类叫做 List...?
  • 类名 List 令人困惑
  • 另外,还有一个名为List 的 C# 类 - 请不要混淆已经存在的类的名称。
  • 如果您使用的是 Visual Studio - 您可以使用 (ctrl+c) 将 JSON 复制到内存中。单击编辑->选择性粘贴->将Json粘贴为类。

标签: c# json serialization json.net deserialization


【解决方案1】:

您的 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&lt;T&gt;T[] 等)。

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

【讨论】:

  • 现在我被困在实际使用反序列化的 json 中:/ 我真的很讨厌这个
  • @Zeq 卡在哪里?这是一个小的demo on .NET Fiddle
  • 好的,非常感谢,我会尝试从这里弄清楚,json也是从服务器下载的,因此它会根据文件而变化
  • @Zeq 什么部分发生了变化?
  • 我用这个json在开始时下载文件client.DownloadFile("https://www.zeroside.co/api/list/" + fetch[0].id + "/" + fetch[0].token, zerolist);
【解决方案2】:

目前,List 有一个名为 privList 实例,尽管名称为:,但它并没有成为列表。要反序列化 JSON 数组 ("priv": [...]),它需要一个数组或类似列表的类型,例如 List&lt;T&gt; 用于某些 T。大概是List&lt;FileThing&gt;,如果我们假设FileThing 实际上是称为List 的第二种类型(你有2 个)。

【讨论】:

  • 我的班级叫list
  • @Zeq 他们不是 both 称为List(至少:不在同一个命名空间中)...因为 这不是合法的 C#...但这不是重点。问题不在于名称......它需要是一个数组或类似列表的类型。您可以将您的 List 类型重命名为 Banana,我所说的一切都将保持不变。
猜你喜欢
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多