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

时间:2018-09-03 11:20:37

标签: 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; }
    }

我不断收到“将值从'字符串'转换为'对象'的错误。

我尝试过: thisthisthisthisthisthisthis,将无法使用。总是相同的错误。显然我遗漏了一些东西,但是已经两天了,我似乎无法弄清楚。尝试将对象类修改为包括所有字段,尝试添加另一个具有list属性的类,甚至尝试将其作为Array传递。

在这一点上,我将不胜感激。

2 个答案:

答案 0 :(得分:7)

问题是您有一个字符串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; }
    

答案 1 :(得分:2)

使用string代替Guid

 public string CustID { get; set; }

由于错误状态:Error converting value string to object,您到达那里的唯一对象是Guid,它可能在对字符串进行反序列化时遇到了问题。