2017-01-23 52 views
0

我有以下的JSON從Documentum的我如何反序列化JSON從Documentum的REST服務

返回
{ 
    "resources" : { 
     "http://identifiers.emc.com/linkrel/repositories" : { 
      "href" : "http://stg1docapp10:7000/dctm-rest/repositories.json", 
      "hints" : { 
       "allow" : ["GET"], 
       "representations" : ["application/xml", "application/json", "application/atom+xml", "application/vnd.emc.documentum+json"] 
      } 
     }, 
     "about" : { 
      "href" : "http://stg1docapp10:7000/dctm-rest/product-info.json", 
      "hints" : { 
       "allow" : ["GET"], 
       "representations" : ["application/xml", "application/json", "application/vnd.emc.documentum+xml", "application/vnd.emc.documentum+json"] 
      } 
     } 
    } 
} 

我想找到的是如何將它轉換成一個類;

我已經試過

Dictionary<String,String> ds = JsonConvert.DeserializeObject<Dictionary<String, String>>(result); 

,我曾嘗試定義下面的類,它反序列化到該。

public class DocumentumServices 
    : IDisposable 
{ 
    public String href { get; set; } 
    public IList<String> hints { get; set; } 

    public void Dispose() 
    { 

    } 
} 
+1

爲什麼不嘗試使用像http://json2csharp.com這樣的在線POCO生成器? – Miki

回答

1

不幸的是,DeserializeObject cannnot做你想要的,只是簡單的。如果你想要一個簡單的解決方案,您可以嘗試使用LINQ到JSON:

var ds = JObject.Parse(result); 
var list = (from doc in ds["resources"] 
      select doc.Values().ToDictionary(k => ((JProperty)k).Name, 
              v => v.Children().First()) into gr 
      select new DocumentumServices() { 
       href = gr["href"].ToString(), 
       hints = (from hnt in gr["hints"] select hint.ToString()).ToList() 
      }).ToList(); 

你甚至可以分解hints進一步像這樣:

public class DocumentumServices 
{ 
    public string href { get; set; } 
    public Dictionary<string, List<string>> hints { get; set; } 
} 
// ... 

var ds = JObject.Parse(result); 
var list = (from doc in ds["resources"] 
      select doc.Values().ToDictionary(k => ((JProperty)k).Name, v => v.Children().First()) into gr 
      select new DocumentumServices() { 
       href = gr["href"].ToString(), 
       hints = (from hint in gr["hints"] 
         select new { 
          Key = hint.Path.Substring(hint.Path.LastIndexOf('.')+1), 
          Value = hint.Children().First().Select(x => x.ToString()).ToList() 
         }).ToDictionary(k => k.Key, v => v.Value) 
      }).ToList(); 

如果你打算在經常使用這個你代碼,你應該把它變成一個自定義的JsonConverter用於DeserializeObject