解析字典
问题描述:
我有两个代码段解析字典
代码1
string json = @"{""properties"":{""name"":""carl""}}";
try
{
MemoryStream stream = GetMemoryStreamFromString(json);
Type type = typeof(Person);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
object obj = serializer.ReadObject(stream);
Debug.WriteLine(obj);
Person person = obj as Person;
}
catch (Exception ee)
{
Debug.WriteLine(ee.Message);
}
//And my classes
[DataContract]
public class Person
{
[DataMember]
public Property properties { set; get; }
public Person() { }
}
[DataContract]
public class Property
{
[DataMember]
public string name { set; get; }
public Property() { }
}
代码2
string json = @"{""properties"":{""name"":""carl""}}";
try
{
MemoryStream stream = GetMemoryStreamFromString(json);
Type type = typeof(Person);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
object obj = serializer.ReadObject(stream);
Debug.WriteLine(obj);
Person person = obj as Person;
}
catch (Exception ee)
{
Debug.WriteLine(ee.Message);
}
//And my class
[DataContract]
public class Person
{
[DataMember]
public Dictionary<string,string> properties { set; get; }
public Person() { }
}
代码1工作正常,但代码2给我例外。这里是日志
数据协定类型'ScrollViewExample.Person'不能被反序列化,因为成员'属性'不公开。公开成员将修复此错误。或者,您可以将其设置为内部,并在程序集中使用InternalsVisibleToAttribute属性,以启用内部成员的序列化 - 请参阅文档以获取更多详细信息。请注意,这样做有一定的安全隐患。
这里的问题是,我没有一个为properties
定义的结构,它可以有任何键,所以我不能为它定义一个类。我发布这个问题,因为我有一个problem和调查后,我发现我无法解析字典。所以我制定我的问题转化为简单的一个,这样你们可以给你的输入
答
不幸的是DataContractJsonSerializer
期待您的JSON数据作为
{"properties":[{"Key":"Name","Value":"Valorie"},{"Key":"Month","Value":"May"},{"Key":"Year","Value":"2013"}]}
我认为使用Json.NET是解析JSON
一个好主意
您是否考虑使用http://json.codeplex.com/而不是框架的序列化程序? – weismat 2013-04-04 07:23:14
不,我不使用它作为'DataContractJsonSerializer'适用于windows-8,我只是将我的代码移植到wp8 – 2013-04-04 07:28:01