C# - 解析值 : {. 路径“[0].Statistics”时遇到意外字符

标签 c# json json.net deserialization json-deserialization

我正在尝试使用以下代码根据我的模型反序列化 JSON 对象:

LoadData<MyModel>(Data.Stats, null);

public void LoadData<TModel>(string data, JsonSerializerSettings jsonSettings) where TModel : class
{
    var mockData = JsonConvert.DeserializeObject<Collection<TModel>>(data, jsonSettings); // ERROR HERE
    Context.SaveChanges();
}

但是我收到一个错误,内容为

Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: {. Path '[0].Statistics', line 7, position 19.'

我的 JSON 对象是:

[
  {
    "Id": 3033,
    "Grade": 3,
    "Statistics": { //ERROR OCCURS ON THIS PROPERTY
      "Avatar.Add": 1,
      "TotalPlays": 36,
      "Game.TotalPlays.Spell_Mem_Words": 27,
      "Book.TotalReads.Count": 23,
      "Game.TotalPlays.Count": 39,
      "Character.TotalPlays.L": 23,
      "Character.TotalPlays.E": 3,
      "TotalPlays.Pick_Vocab": 16,
      "Character.TotalPlays.R": 22
    }
  }
]

对象模型是:

public class MyModel
{
    public int Id { get; set; }
    public int Grade { get; set; }
    public string Statistics { get; set; } 
}

我尝试过的事情

(1) Using json lint我已确保 json 字符串有效。

(2) 在 javascript 中,序列化带有反引号的对象是可行的。反引号在 C# 中不起作用 JS Fiddle

(3) 尝试使对象模型中的统计属性使用名为 stats 的类,而不是像这样的字符串

public class Stats 
{
    public string Label { get; set;}
    public int Value { get; set; }
}

(4) 尝试了几乎所有 the answers on this SO post

不幸的是我还没有解决这个问题。有什么想法吗?

最佳答案

我能够使用此 MCVE 重现问题:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DeserializeJson
{
    /**
     * REFERENCE:
     * https://stackoverflow.com/questions/53562566/
     *
     * ORIGINAL ERROR:
     * "Unexpected character encountered while parsing value: {. Path '[0].Statistics', line 5, position 19."
     */
     public class Stats
     {
         public string Label { get; set; }
         public int Value { get; set; }
     }

     public class MyModel
     {
         public int Id { get; set; }
         public int Grade { get; set; }
         public string Statistics { get; set; }
     }

    class Program
    {
        static Collection<MyModel> LoadData(string data)
        {
            var retval = JsonConvert.DeserializeObject<Collection<MyModel>>(data);
            return retval;
        }

        static void Main(string[] args)
        {
            try
            {
                string s = File.ReadAllText(@"test-data.json");
                JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                {
                    Formatting = Newtonsoft.Json.Formatting.Indented
                };
                Collection <MyModel> mockData = Program.LoadData(s);
                System.Console.WriteLine("#/items= " + mockData.Count);
                foreach (MyModel item in mockData)
                {
                    System.Console.WriteLine("  id= {0}, Grade={1}, Statistics={2}", item.Id, item.Grade, item.Statistics.ToString());
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("ERROR:", ex);
            }
        }
    }
}

我能够通过以下方式修复它:

  1. 详细阐述class Stats的定义,然后
  2. 类 MyModel 的定义中使用统计信息:

    public class Stats
    {
        public int AvatarAdd { get; set; }
        public int TotalPlays { get; set; }
        public int GameTotalPlaysSpellMemWords { get; set; }
        public int BookTotalReadsCount { get; set; }
        public int GameTotalPlaysCount { get; set; }
        public int CharacterTotalPlaysL { get; set; }
        public int CharacterTotalPlaysE { get; set; }
        public int TotalPlaysPick_Vocab { get; set; }
        public int CharacterTotalPlaysR { get; set; }
    }
    
    public class MyModel
    {
        public int Id { get; set; }
        public int Grade { get; set; }
        public Stats Statistics { get; set; }
    }
    

您有多种选择(包括逐字使用上面的示例)。我的建议是将“统计”分解为更小的模型类。

关于C# - 解析值 : {. 路径“[0].Statistics”时遇到意外字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53562566/

相关文章:

c# - 如何对 CSV 文件使用 SQL

c# - 我可以保存回发状态并恢复吗?

c# - nhibernate 连接表和自定义类型

java - 通过json发送请求参数

python - 如何使用 Python 抓取类别维基百科页面类别中的子类别和页面

C# Json 到对象字典

c# - JSON.NET 反序列化存储为属性的 JSON 对象

c# - 如何复制 Azure 表

php - 从静态文件 JSON 提要更新数据库

c# - System.Text.Json 默认将 double 类型的值 1.0 序列化为 int 类型的值 1