2017-09-21 43 views
2

我有我想DeserializeObject与innerDictionary和innermostClass一个outerDictionary作为所以JSON:反序列化嵌套JSON到词典,串和类

var entityMap = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, fieldClass>>>(File.ReadAllText("map.json")); 

然而,innerDictionary可以具有字符串:字符串而不是string:innerMostClass。

{ 
"Client": { 
    "__class__": "contact", 

    "ClientId": { 
     "__field__": "new_ndisclientid", 
     "__type__": "string" 
    }, 
    "GivenName": { 
     "__field__": "firstname", 
     "__type__": "string" 
    }, 
}, 
"Case": { 
    "__class__": "contact", 

    "CaseId": { 
     "__field__": "new_ndiscaseid", 
     "__type__": "string" 
    } 
} 
} 

有没有办法做到这一点?我不想把它全部放到类中。

是否有可能使用自定义JsonConverter来做到这一点?

编辑:为清晰起见,将classname重命名为entityName。 ClientId和GivenName将被反序列化为fieldClasses。

回答

2

您可以使用动态或如果你想分开内部类

public class Client 
{ 
    public string __entityName__ { get; set; } 
    public Dictionary<string, string> ClientId { get; set; } 
    public Dictionary<string, string> GivenName { get; set; } 
} 
var deserializedWithClass = JsonConvert.DeserializeObject<Dictionary<string, Client>>(json); 
+0

我试过动态的,但希望它是一类或类似物体,而不是内部类

var json = "{\r\n\t\"Client\": {\r\n\t\t\"__entityName__\": \"contact\",\r\n\r\n\t\t\"ClientId\": {\r\n\t\t\t\"__field__\": \"new_ndisclientid\",\r\n\t\t\t\"__type__\": \"string\"\r\n\t\t},\r\n\t\t\"GivenName\": {\r\n\t\t\t\"__field__\": \"firstname\",\r\n\t\t\t\"__type__\": \"string\"\r\n\t\t}\r\n\t}\r\n}"; var deserialized = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, dynamic>>>(json); List<object> values = deserialized.SelectMany(result => result.Value).Cast<object>().ToList(); 

,如果可能的话。我希望该类具有方法,并且动态数据类型在Visual Studio中没有IntelliSense。 –

+0

使用类而不是动态更新答案 – Abhay

+0

将根变为类是另一种方法。但我认为它必须是一个Dictionary/List,因为根并不总是一个Client。可能会说,一个具有不同内部类别的案例,但它们具有相同的字段。我已经更新了原来的帖子JSON以显示我的意思。 –