【问题标题】:Read Error when loading JSON array in Newtonsoft C#在 Newtonsoft C# 中加载 JSON 数组时读取错误
【发布时间】:2018-05-15 05:38:13
【问题描述】:

我在 C# 中使用 Newtonsoft JSON 解析器。 JSON 似乎格式正确,但我收到一个没有意义的读取错误。 JSON 应该自动反序列化并加载到类实例中。

类:

class FilterMatrix {
    public int ID { get; set; }
    public int ParentID { get; set; }
}

反序列化代码:

string fileName = @"C:\Users\accounts.json";
FilterMatrix kernel = JsonConvert.DeserializeObject<FilterMatrix>(File.ReadAllText(fileName));

JSON 文件内容:

{"Features":[{"ID":0,"ParentID":0},{"ID":0,"ParentID":0}]}

错误:

Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: {. Path 'Features', line 1, position 14.'

【问题讨论】:

  • 错误信息似乎有点奇怪,但 JSON 看起来并不代表 FilterMatrix 对象
  • 我刚刚意识到我的班级需要一个 Features 属性。它应该是集合类型吗?列表?

标签: c# arrays json list


【解决方案1】:

好吧,至少 JSON 的结构需要与您的类层次结构相匹配。工作示例:

class Program
{

    static void Main(string[] args)
    {
        var root = JsonConvert.DeserializeObject<Root>(File.ReadAllText("file.json"));
    }

}

public class Root
{
    public List<FilterMatrix> Features { get; set; }
}

public class FilterMatrix
{
    public int ID { get; set; }
    public int ParentID { get; set; }
}

【讨论】:

    【解决方案2】:

    谢谢,吉恩。

    当我看到你的帖子时,我基本上想出了这个。我从来没有在一个班级中有多个班级。我想我假设会自动生成一个类数组:-/

    JSON 脚本:

    {"Features":[{"ID":0,"ParentID":0},{"ID":0,"ParentID":0}]}
    

    反序列化:

    kernel = JsonConvert.DeserializeObject<FilterMatrix>(File.ReadAllText(fileName));
    

    我的课:

    class FilterMatrix {
        private List<Feature> features = new List<Feature>();  
        public List<Feature> FeaturesList
        {
            get { return features; }
            set { features = value; }
        }
    }
    
    class Feature {
        public int ID { get; set; }
        public int ParentID { get; set; }
    }
    

    我通过索引访问元素:

    kernel.FeaturesList[0].ID
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 2021-10-13
      相关资源
      最近更新 更多