简体   繁体   English

RestSharp 反序列化 JSON 字典

[英]RestSharp Deserialize JSON Dictionary

I'm having some trouble using RestSharp to deserialize a JSON response from a REST service, but I suspect this would happen with Newtonsoft or other libraries, it's a serialization thing rather than a library-specific thing.我在使用 RestSharp 反序列化来自 REST 服务的 JSON 响应时遇到了一些麻烦,但我怀疑 Newtonsoft 或其他库会发生这种情况,这是序列化的事情而不是特定于库的事情。

The response is part dictionary/collection, part response code, but the dictionary/collection elements aren't presented as an array, but items with a numeric property name.响应是部分字典/集合,部分响应代码,但字典/集合元素不是作为数组呈现,而是具有数字属性名称的项目。

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

I'm trying to deserialize this to a POCO, but I'm not sure how to go about deserializing those numbered items.我正在尝试将其反序列化为 POCO,但我不确定如何反序列化这些编号的项目。 Has anyone done this before, or know how I can do this?有没有人以前做过这个,或者知道我怎么做? I'm not precious about the POCO, anything that works is fine.我对 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; }
}

I have achieved it by the following code:我通过以下代码实现了它:

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; }
    }

Eventually managed to resolve this using the following (the type that came back was a JObject which is why it wouldn't cast to IDictionary per the @FaizanRabbani answer.最终设法使用以下方法解决了这个问题(返回的类型是 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM