使用NewtonSoft反序列化List <object>。无法转换IList

时间:2018-05-02 21:28:04

标签: c# json.net json-deserialization

我正在尝试解析Comment对象列表from here。注释对象是leankit命名空间中的一个类:LeanKit.API.Client.Library.TransferObjects.Comment但是我在下面的块的最后一行中得到一个错误,特别是responseString

  

无法从'System.Collections.Generic.IList'转换为字符串

为什么我会这样?我正在指定一个专门为反序列化列表创建的自定义类:

public class MyCommentList
{
    public string ReplyText { get; set; }
    public List<Comment> ReplyData { get; set; }
    public string ReplyCode { get; set; }
} 

调用类

var url = "https://" + acctName + ".leankit.com/kanban/api/card/getcomments/" + boardid + "/" + cardid;
var responseString = await url.WithBasicAuth("xxx", "yyy").GetJsonListAsync();
MyCommentList mycomment = JsonConvert.DeserializeObject<MyCommentList>(responseString);

调用该类的更简洁版本(使用Flurl):

var url = "https://" + acctName + ".leankit.com/kanban/api/card/getcomments/" + boardid + "/" + cardid;
MyCommentList mycomment = await url.WithBasicAuth("xxx", "yyy").GetAsync().ReceiveJson<MyCommentList>();

JSON结构(来自上面的链接)在这里转载:

{
  "ReplyData": [
    [
      {
        "Id": 256487698,
        "Text": "First comment for this card.",
        "TaggedUsers": null,
        "PostDate": "10/14/2015 at 04:36:02 PM",
        "PostedByGravatarLink": "3ab1249be442027903e1180025340b3f",
        "PostedById": 62984826,
        "PostedByFullName": "David Neal",
        "Editable": true
      }
    ]
  ],
  "ReplyCode": 200,
  "ReplyText": "Card comments successfully retrieved."
}

1 个答案:

答案 0 :(得分:3)

在JSON中,"ReplyData"是一个2d锯齿状数组:

{
  "ReplyData": [ [ ... ] ],
}

在你的模型中,它是一个列表:

public List<Comment> ReplyData { get; set; }.  

您需要将其更改为public List<List<Comment>> ReplyData { get; set; }以反映实际的JSON:

public class MyCommentList
{
    public string ReplyText { get; set; }
    public List<List<Comment>> ReplyData { get; set; }
    public string ReplyCode { get; set; }
} 

我认为Comment取自https://github.com/LeanKit/LeanKit.API.Client/blob/master/LeanKit.API.Client.Library/TransferObjects/Comment.cs

如果有时可能是1d数组,有时是2d数组,则可能需要将SingleOrArrayConverter<Comment>this answer应用到 How to handle both a single item and an array for the same property using JSON.net 通过Brian Rogers如此:

public class MyCommentList
{
    public string ReplyText { get; set; }

    [JsonProperty(ItemConverterType = typeof(SingleOrArrayConverter<Comment>))]
    public List<List<Comment>> ReplyData { get; set; }
    public string ReplyCode { get; set; }
} 

工作样本.Net小提琴here