将JSON字符串反序列化为Dictionary<string,object>。

44

我有这个字符串:

[{ "processLevel" : "1" , "segments" : [{ "min" : "0", "max" : "600" }] }]

我正在对对象进行反序列化:

object json = jsonSerializer.DeserializeObject(jsonString);

这个物体看起来像:

object[0] = Key: "processLevel", Value: "1"
object[1] = Key: "segments", Value: ...

试图创建一个字典:

Dictionary<string, object> dic = json as Dictionary<string, object>;

但是dic得到的是null

问题可能是什么?


如果“json as IDictionary<string, object>”,则变量 json = JsonConvert.DeserializeObject<ExpandoObject>(jsonString,new ExpandoObjectConverter()); //也许 ExpandoObject 是您想要的动态对象。 - TamusJRoyce
5个回答

44

参考mridula的答案以了解为什么会出现null。但如果您想直接将json字符串转换为字典,可以尝试以下代码片段。

    Dictionary<string, object> values = 
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

5
我想将反序列化到一个包含字典和其他普通属性的类中。我该怎么做? - Shilan
对于我的情况,我注意到该属性是只读的。因此,反序列化过程无法设置该值。 在我的情况下,我将其更改为非只读,并且它起作用了! 但是,如果您希望将其保持为只读,我认为您可以创建一个接收该属性的构造函数。 - Henrique

10

我喜欢这种方法:

using Newtonsoft.Json.Linq;
//jsonString is your JSON-formatted string
JObject jsonObj = JObject.Parse(jsonString);
Dictionary<string, string> dictObj = jsonObj.ToObject<Dictionary<string, object>>();

您现在可以使用dictObj作为字典访问任何您想要的内容。如果您更喜欢将值作为字符串获取,也可以使用Dictionary<string, string>


8
感谢您包含了 using 行,因为太多的例子都没有包括它。 - dansalmo
在上面的例子中,应该是 jsonObj.ToObject<Dictionary<string, string>>(); - Arsen Khachaturyan
你如何将 dictObj 转换回 JSON 格式的字符串? - wueli

7
MSDN文档中关于as关键字的说明表明,语句expression as type等同于语句expression is type ? (type)expression : (type)null。如果运行json.GetType(),它将返回System.Object[]而不是System.Collections.Generic.Dictionary
在这种类型复杂的情况下,我使用像Json.NET这样的API来反序列化json对象。您可以编写自己的反序列化器:
class DictionaryConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        Throw(new NotImplementedException());            
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Your code to deserialize the json into a dictionary object.

    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        Throw(new NotImplementedException());   
    }
}

然后您可以使用此序列化程序将JSON读取到字典对象中。这里是一个示例


这个相关问题的答案包含了解决方案的完整源代码:https://dev59.com/-mgu5IYBdhLWcg3wHjl7#31250524 - smdrager

1

我也遇到了同样的问题,并找到了解决方法

  • 非常简单
  • 没有错误
  • 在运营产品上测试过

步骤1)创建一个具有2个属性的通用类

     public class CustomDictionary<T1,T2> where T1:class where T2:class
      {
          public T1 Key { get; set; }
          public T2 Value { get; set; }
      }

步骤2)创建新类并继承第一个类

  public class SectionDictionary: CustomDictionary<FirstPageSectionModel, List<FirstPageContent>> 
    { 

    }

第三步)替换字典和列表。
public Dictionary<FirstPageSectionModel, List<FirstPageContent>> Sections { get; set; }

并且

 public List<SectionDictionary> Sections { get; set; }

步骤4)轻松序列化或反序列化
 {
     firstPageFinal.Sections.Add(new SectionDictionary { Key= section,Value= contents });
     var str = JsonConvert.SerializeObject(firstPageFinal);
     var obj = JsonConvert.DeserializeObject<FirstPageByPlatformFinalV2>(str);
 }

非常感谢。

“没有错误” - 我已经至少数出了你代码中的4个错误。很抱歉,但我给这个答案投了反对票。 - Dai
2
那么这四个错误是什么? - Tyler Montney

-1
问题在于该对象不是类型为Dictionary<string,object>或兼容类型,因此您无法直接进行转换。我会创建一个自定义对象并使用反序列化。
public class DeserializedObject{
    public string processLevel{get;set;}
    public object segments{get;set}
}

IEnumerable<DeserializedObject> object=jsonSerializer.Deserialize<IEnumerable<DeserializedObject>>(json);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接