如何从Documentum REST Service

时间:2017-01-23 17:41:17

标签: c# json documentum

我从Documentum

返回了以下JSON
{
    "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 个答案:

答案 0 :(得分:1)

不幸的是,DeserializeObject无法完成您想要的任务。如果您想要一个简单的解决方案,您可以尝试使用LINQ to 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