2013-11-01 61 views
0

我有一个有趣的问题,其中我的JSON被返回给相同的URI调用,可能会根据用户的标识略有不同。我不知道随着时间的推移可能会改变所有差异的组合。例如,对同一个URL的三个不同请求可以返回这三个不同的JSON表示。Restsharp和反序列化到字典

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

我所试图做的是要么返回包含在listALL事情的字典集合是不常见的,并没有被反序列化或者没有包含在list中的所有东西的字典。一些假设是,如果需要,列表中的所有值都可以视为字符串。

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

回答

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

当然的适应方法将包含您的检查电路(如失败在字典等)

+0

阿哈没想过扭转它,看起来不错,会试一试。 – Rippo