C# 如何将以下JSON数组转换为IDictionary<;字符串,对象>;?

C# 如何将以下JSON数组转换为IDictionary<;字符串,对象>;?,c#,json,json.net,C#,Json,Json.net,下面是我想转换为IDictionary [ { "8475": 25532 }, { "243": 521 }, { "3778": 15891 }, { "3733": 15713 } ] 当我尝试使用 JsonConvert.DeserializeObject<IDictionary<string, object>>((string)jarray); JsonConvert.DeserializeOb

下面是我想转换为
IDictionary

[
  {
    "8475": 25532
  },
  {
    "243": 521
  },
  {
    "3778": 15891
  },
  {
    "3733": 15713
  }
]
当我尝试使用

JsonConvert.DeserializeObject<IDictionary<string, object>>((string)jarray);
JsonConvert.DeserializeObject((字符串)jarray);
我的错误是:

无法将“jarray”(其实际类型为“Newtonsoft.Json.Linq.jarray”)强制转换为“string”


JSON反序列化程序只需要一个字符串。

如果您已经有了
JArray
,那么您所要做的就是将其转换为字典

大致如下:

IDictionary<string,object> dict = jarray.ToDictionary(k=>((JObject)k).Properties().First().Name, v=> v.Values().First().Value<object>());
Dictionary<string, object> myDictionary = new Dictionary<string, object>();

foreach (JObject content in jarray.Children<JObject>())
{
    foreach (JProperty prop in content.Properties())
    {
        myDictionary.Add(prop.Name, prop.Value);
    }
}
IDictionary dict=jarray.ToDictionary(k=>((JObject)k).Properties().First().Name,v=>v.Values().First().Value());


不过,我认为可能有更好的办法把它转换成字典。我会继续查找。

JsonConvert.DeserializeObject方法采用JSON字符串,换句话说,是一个序列化的对象。
您有一个反序列化的对象,因此必须首先对其进行序列化,这实际上是毫无意义的,因为您在
JArray
对象中就有了所需的所有信息。如果您的目标只是从数组中获取作为键值对的对象,则可以执行以下操作:

IDictionary<string,object> dict = jarray.ToDictionary(k=>((JObject)k).Properties().First().Name, v=> v.Values().First().Value<object>());
Dictionary<string, object> myDictionary = new Dictionary<string, object>();

foreach (JObject content in jarray.Children<JObject>())
{
    foreach (JProperty prop in content.Properties())
    {
        myDictionary.Add(prop.Name, prop.Value);
    }
}
Dictionary myDictionary=newdictionary();
foreach(jarray.Children()中的作业对象内容)
{
foreach(content.Properties()中的JProperty属性)
{
添加(prop.Name,prop.Value);
}
}

要将您的
JArray
转换为字符串,您需要为每个元素分配字典的键和值。马里奥给出了一个非常准确的方法。但是,只要您知道如何将每个项目转换为所需的类型,就有一种更漂亮的方法。以下示例适用于
字典
,但可应用于任何
类型

//Dictionary<string, string>
var dict = jArray.First() //First() is only necessary if embedded in a json object
                 .Cast<JProperty>()
                 .ToDictionary(item => item.Name,
                               item => item.Value.ToString()); //can be modified for your desired type
//字典
var dict=jArray.First()//First()仅在嵌入json对象时才是必需的
.Cast()
.ToDictionary(item=>item.Name,
item=>item.Value.ToString())//可以根据所需类型进行修改

括号中的数组?这是有效的JSON吗?如果您已经有一个
JArray
实例,那么为什么要转换为字符串以转换回某个JSON.NET类型以转换为
IDictionary
?(你不能反序列化到接口,它必须是一个具体类型。)如果你真的想从jarray中提取字符串,为什么不调用
ToString()
方法呢?你的JSON字符串是无效的。Mario,当我尝试以下操作时,JsonConvert.DeserializeObject(jarray.ToString());我收到消息-其他信息:无法将当前JSON数组(例如[1,2,3])反序列化为'System.Collections.Generic.IDictionary`2[System.String,System.Object]'类型,因为该类型需要一个JSON对象(例如{“name”:“value”})才能正确反序列化。