我想反序列化這個JSON到一個對象,但我不能達到解決方案。自定義反序列化從json對象字符串
JSON格式:
{"option1":
{"field1":"true","field2":"false"},
"option2":
{"field1":"true","field2":"false"}}
我有以下對象:
[Serializable]
public class genericFieldOptions
{
public string option { get; set; }
public string field { get; set; }
public bool value{ get; set; }
}
,然後在 「解串器」:
public class genericFieldsConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get
{
return new[] { typeof(genericFieldOptions) };
}
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
List<genericFieldOptions> p = new List<genericFieldOptions>();
foreach (var entry in dictionary.Keys)
{
try
{
Dictionary<string, Boolean> test = (Dictionary<string, Boolean>)dictionary[entry];//error
p.Add(new genericFieldOptions { key = entry, field1=test["field1"],field2=test["field2"] });
}
catch { }
}
return p;
}
召喚:
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new genericFieldsConverter() });
var example= serializer.Deserialize<List<genericFieldOptions>>(json);
如何才能以Dictionary<string, Dictionary<string,boolean>>
訪問IDictionary<string, object>
?還是僅僅是不可能的?
我在做什麼錯?有沒有另一種簡單的方法來做到這一點?
事實上還有另一種簡單的方法 - 使用[Json.NET(http://www.newtonsoft.com/json):-) –
你可以從你的問題複製的JSON字符串,並把光標在需要創建模型的命名空間中。 Goto - Edit-PasteSpecial->作爲JSON CLASS ......然後使用NewtonSoft.Json添加一個包;在頂部和分配標題爲模型/類的每個屬性作爲[JsonProperty(「option1或option2」)] .....提示 –