如何从 Documentum REST 服务反序列化 JSON

How can I deserialize JSON from Documentum REST Service

我从 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"]
            }
        }
    }
}

我想要找到的是如何将其转换为 class;

我试过了

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

我尝试定义以下 class 并将其反序列化为

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

    public void Dispose()
    {

    }
}

不幸的是,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 一起使用。