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

oha*_*nho 32 .net c# json

我有这个字符串:

[{ "processLevel" : "1" , "segments" : [{ "min" : "0", "max" : "600" }] }]
Run Code Online (Sandbox Code Playgroud)

我正在反序列化该对象:

object json = jsonSerializer.DeserializeObject(jsonString);
Run Code Online (Sandbox Code Playgroud)

该对象看起来像:

object[0] = Key: "processLevel", Value: "1"
object[1] = Key: "segments", Value: ...
Run Code Online (Sandbox Code Playgroud)

并尝试创建一个字典:

Dictionary<string, object> dic = json as Dictionary<string, object>;
Run Code Online (Sandbox Code Playgroud)

dic得到null.

可能是什么问题?

san*_*ngh 32

请参阅mridula的答案,了解为何您获得null.但是如果你想直接将json字符串转换为字典,你可以尝试下面的代码片段.

    Dictionary<string, object> values = 
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
Run Code Online (Sandbox Code Playgroud)

  • 但我想反序列化为具有字典和其他普通属性属性的类。我怎样才能做到这一点? (5认同)

mri*_*ula 6

MSDN文档as关键字指出声明expression as type是等效的声明expression is type ? (type)expression : (type)null.如果你运行json.GetType()它将返回System.Object[]而不是System.Collections.Generic.Dictionary.

在这些情况下,我想要反序列化json对象的对象类型很复杂,我使用像Json.NET这样的API.您可以编写自己的反序列化器:

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());   
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用此序列化程序将json读入您的字典对象.这是一个例子.


Bla*_*g23 6

我喜欢这种方法:

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

您现在可以使用dictObj字典作为任何内容访问.Dictionary<string, string>如果您希望将值作为字符串获取,也可以使用.

  • 感谢包括`using`行,太多的例子都没有. (2认同)