我有这个字符串:
[{ "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
。
可能是什么问题?
答案 0 :(得分:28)
请参阅mridula的答案,了解为何您获得null。但是如果你想直接将json字符串转换为字典,你可以尝试下面的代码片段。
Dictionary<string, object> values =
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
答案 1 :(得分:6)
as
关键字的MSDN documentation表示语句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());
}
}
然后您可以使用此序列化程序将json读入您的字典对象。这是一个example。
答案 2 :(得分:5)
我喜欢这种方法:
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>
。
答案 3 :(得分:0)
我遇到了同样的问题,并找到了解决方案
第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>>
{
}
步骤3)替换字典和列表
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 :(得分:-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);