RestSharp反序列化JSON字典

时间:2018-02-12 15:10:43

标签: c# json serialization json.net restsharp

我在使用RestSharp从REST服务反序列化JSON响应时遇到了一些麻烦,但我怀疑这会发生在Newtonsoft或其他库中,它是序列化的东西,而不是特定于库的东西。

响应是部分字典/集合,部分响应代码,但字典/集合元素不是以数组形式呈现,而是具有数字属性名称的项目。

{ "StatusCode": 1, "1": { forename: "Test", surname: "Subject", addressLine1: "1 The Street" }, "2": { ... }, "3": { ... } ... }

我试图将其反序列化为POCO,但我不确定如何对这些编号项进行反序列化。有没有人以前做过这个,或者知道我怎么做到这一点?我对POCO并不珍贵,任何有效的方法都可以。

public class ServiceResponse
{
    public int StatusCode { get; set; }
    public Dictionary<int, ServiceResponseItem> Items { get; set; }
}

public class ServiceResponseItem 
{
    public string Forename { get; set; }
    public string Surname { get; set; }
    public string AddressLine1 { get; set; }
}

2 个答案:

答案 0 :(得分:1)

我通过以下代码实现了它:

dynamic res = JsonConvert.DeserializeObject(
                "{ \"StatusCode\": 1, \"1\": { \"forename\": \"Test\", \"surname\": \"Subject\", \"addressLine1\": \"1 The Street\" }}");
            IDictionary<string, JToken> datas = res;
            foreach (var dt in datas.Skip(1))
            {
                Info newInfo = JsonConvert.DeserializeObject<Info>(dt.Value.ToString());
            }


public class StackOverFlow
    {
        public int StatusCode { get; set; }
        public Info Info { get; set; }
    }

    public class Info
    {
        public string forename { get; set; }
        public string surname { get; set; }
        public string addressLine1 { get; set; }
    }

答案 1 :(得分:0)

最终设法使用以下方法解决了这个问题(返回的类型是JObject,这就是为什么它不会根据@FaizanRabbani答案转换为IDictionary。

public StackOverflow Parse(string json)
{
    StackOverflow response = new StackOverflow();
    response.Items = new List<Info>();

    dynamic res = JsonConvert.DeserializeObject(json);
    response.StatusCode = res.StatusCode;

    foreach (JProperty item in res)
    {

        if (item.Name != "StatusCode")
        {
            var infoItem = JsonConvert.DeserializeObject<Info>(item.Value.ToString());
            response.Items.Add(infoItem);
        }
    }


    return response;
}