【问题标题】:Restsharp and deserialization to a dictionaryRestsharp和反序列化到字典
【发布时间】:2013-11-01 20:33:17
【问题描述】:

我有一个有趣的问题,我的JSON 为同一个 URI 调用返回,可能会根据用户的 ID 略有不同。我不知道所有差异的组合,因为事情可能会随着时间而改变。例如,对同一 URL 的三个不同请求可能会返回这三种不同的 JSON 表示。

{ "success":true, "total":1, "list":[{
    "uid":"24",
    "firstname":"Richard",
    "question1":"Y"}
]}

{ "success":true, "total":1, "list":[{
    "uid":"25",
    "firstname":"Fred",
    "question2":"Yes"}
]}

{ "success":true, "total":1, "list":[{
    "uid":"26",
    "firstname":"Bob",
    "surname":"Wilde",
    "question3":"Cat"}
]}

注意第一个调用包含Question1,第二个调用包含Question2,第三个调用包含surname and Question3

反序列化的代码如下:-

var result = client.Execute<ResultHeader<Customer>>(request);


public class ResultHeader<T>
{
    public bool Success { get; set; }
    public int Total { get; set; }
    public List<T> List { get; set; }
}

public class Customer
{
   public string Firstname { get; set; }  //This is always returned in the JSON

   //I am trying to get this...
   public Dictionary<string, string> RemainingItems { get; set; }
}

我想要做的是要么返回 ALL 包含在 list 中的不常见且尚未反序列化的东西的字典集合,要么返回包含在 list 中的所有东西的字典.一些假设是,如果需要,列表中的所有值都可以视为字符串。

这可以使用 RESTSharp 吗?我不想在编译时使用动态,因为我不知道所有的可能性。基本上,一旦我有了字典,我就可以在运行时循环和映射我需要的位置。

【问题讨论】:

    标签: c# dictionary restsharp json-deserialization


    【解决方案1】:

    我会做一个中间步骤:

    var resultTmp = client.Execute<ResultHeader<Dictionary<string,string>>>(request);
    var finalResult = AdaptResult(resultTmp);
    

    其中AdaptResult可以实现如下:

    static ResultHeader<Customer> AdaptResult(
                             ResultHeader<Dictionary<string, string>> tmp)
    {
        var res = new ResultHeader<Customer>();
        res.Success = tmp.Success;
        res.Total = tmp.Total;
        res.List = new List<Customer>();
        foreach (var el in tmp.List)
        {
            var cust = new Customer();
            cust.Firstname = el["Firstname"];
            cust.RemainingItems = 
                el.Where(x => x.Key != "Firstname")
                  .ToDictionary(x => x.Key, x => x.Value);
            res.List.Add(cust);
        }
        return res;
    }
    

    当然,适应方法将包含您的检查逻辑(例如,如果所有问题都在字典中,则失败等)

    【讨论】:

    • 啊哈没想过要倒车,看起来不错,试试看。
    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多