2013-11-01 62 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