c# - 从 json 转换为 List<object> 导致异常

标签 c# json

所以这是我的问题,我有一个 API 设置,它以 JSON 字符串格式从 Azure 存储表返回结果:

   [{
        "CustID": "f3b6.....0768bec",
        "Title": "Timesheet",
        "CalendarID": "AAMkADE5ZDViNmIyLWU3N2.....pVolcdmAABY3IuJAAA=",
        "PartitionKey": "Project",
        "RowKey": "94a6.....29a4f34",
        "Timestamp": "2018-09-02T11:24:57.1838388+03:00",
        "ETag": "W/\"datetime'2018-09-02T08%3A24%3A57.1838388Z'\""
    }, {
        "CustID": "5479b.....176643c",
        "Title": "Galaxy",
        "CalendarID": "AAMkADE5Z.......boA_pVolcdmAABZ8biCAAA=",
        "PartitionKey": "Project",
        "RowKey": "f5cc....86a4b",
        "Timestamp": "2018-09-03T13:02:27.642082+03:00",
        "ETag": "W/\"datetime'2018-09-03T10%3A02%3A27.642082Z'\""
    }]

我正在尝试将其转换回 Project 对象:

public class Project : TableEntity
    {
        public Project() { }

        public Project(string rKey, string pKey = "Project")
        {
            this.PartitionKey = pKey;

            this.RowKey = rKey;
        }

        public Guid CustID { get; set; }
        public string Title { get; set; }
        public string CalendarID { get; set; }
    }

我不断收到“将值从‘字符串’转换为‘对象’时出错。

我试过: this , this , this , this , this , thisthis它不会工作。总是同样的错误。很明显我遗漏了一些东西,但是已经两天了,我似乎无法弄清楚。尝试修改对象类以包含所有字段,尝试添加另一个具有列表属性的类,甚至尝试将其作为数组传递。

在这一点上,我将不胜感激任何形式的帮助。

最佳答案

问题是您有一个字符串 CustID 无法反序列化为 Guid

您可以使用 JsonConverter 在反序列化时将 string 转换为 Guid(在 JSON.NET 中可用) :

public class GuidJsonConverter : JsonConverter<Guid>
{
    public override void WriteJson(JsonWriter writer, Guid value, JsonSerializer serializer)
    {
        writer.WriteValue(value.ToString());
    }

    public override Guid ReadJson(JsonReader reader, Type objectType, Guid existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        string s = (string)reader.Value;

        return new Guid(s);
    }
}

两种使用方式:

  • 将转换器实例传递给 DeserializeObject 方法(示例 here)
  • [JsonConverter(typeof(GuidJsonConverter))] 应用于 CustID 属性

    [JsonConverter(typeof(GuidJsonConverter))]
    public Guid CustID { get; set; }
    

关于c# - 从 json 转换为 List<object> 导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52148758/

相关文章:

javascript - 迭代 JSON 以创建导航

javascript - ng-show if json 返回 [false] with angularjs

c# - 如何获取多个类别的关键字匹配数?

c# - 如何获取目录的完整路径

java - Play 框架中的 POJO 到 JSON

javascript - 如何将嵌套的 JSON 数据结构缩减为 map JavaScript

javascript - JSON 响应节点的 JS 错误

c# - 试图从 txt 文件填充文本框和 ListView

c# - System.Collections.IEnumerator 对象的意外行为

c# - 基于key的异步锁