I have the following JSON returned from Documentum
{
"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"]
}
}
}
}
What I am trying to find is how to convert this into an class;
I have tried
Dictionary<String,String> ds = JsonConvert.DeserializeObject<Dictionary<String, String>>(result);
and I have tried defining the following class and deserializing it into that.
public class DocumentumServices
: IDisposable
{
public String href { get; set; }
public IList<String> hints { get; set; }
public void Dispose()
{
}
}
Unfortunately, DeserializeObject
cannnot do what you want that simply. If you want a simple solution, you may try to use 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();
You can even decompose hints
further like so:
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();
If you're intended to use this often in your code, you should make it into a custom JsonConverter
to use with DeserializeObject
.