如何使用Newtonsoft.Json.Linq

时间:2018-07-23 08:42:29

标签: c# json unity3d mono json.net

我有这个JObject:

  

[{“诊断后使用抗生素”:[“阿奇霉素”,“头孢曲松”,   “头孢泊肟酯”,“利奈唑胺”,“万古霉素口服液”,   “盐酸环丙沙​​星”,“氨苄青霉素钠”],“城市”:[“特拉维夫”   “” Beersheba“,”耶路撒冷“,”海法“],”性别代码“:[” M“,” F“,” E“]}]]

我想将此JObject转换为常规对象,所以我尝试使用ToObject()方法:

Dictionary<string, object> dictObj = new Dictionary<string, object>();
dictObj = myJsonObj.ToObject<Dictionary<string, object>>();

但是代码由于以下错误而崩溃:

  

JsonSerializationException:无法将当前JSON数组(例如[1,2,3])反序列化为类型'System.Collections.Generic.Dictionary`2 [System.String,System.Object]',因为该类型需要JSON对象(例如{“ name”:“ value”})正确反序列化。

如何将JObject转换为常规对象?

2 个答案:

答案 0 :(得分:0)

尝试一下:

Dictionary<string, object> dictObj = new Dictionary<string, List<string>>();
dictObj = myJsonObj.ToObject<Dictionary<string, List<string>>>();

答案 1 :(得分:0)

我认为您的问题是,您想对一个数组进行字典灭菌。无论如何,您可能想重新考虑自己在做什么。但是,您将获得Dictionary<string,List<string>>

var json = @"[
{
""Antibiotic after diagnosis"": [""Azithromycin"", ""CeftriaXONE"", ""Cefpodoxime Proxetil"", ""Linezolid"", ""Vancomycin Oral Liquid"", ""Ciprofloxacin HCl"", ""Ampicillin Sodium""], 
""City"": [""Tel Aviv"", ""Beersheba"", ""Jerusalem"", ""Haifa""], 
""Gendercode"": [""M"", ""F"", ""E""]
}]";

            var myJsonObj = JArray.Parse(json);

            Dictionary<string,List<string>> dictObj = myJsonObj.Select(i => 
            i.Cast<JProperty>().ToDictionary(
                k => k.Name, 
                v => v.Value.Select(t => t.Value<string>()).ToList())).ToArray().First();

也请看看How do I use JSON.NET to deserialize into nested/recursive Dictionary and List?,因为正如@dbc所提到的,如果您需要的话,这可能是重复的。