简体   繁体   English

从JSON Windows Phone解析字典

[英]Parse dictionary from json windows phone

I have two piece of code 我有两段代码

Code1 代码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() { }
}



Code2 码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() { }
}

Code1 works fine but Code2 give me the exception. Code1工作正常,但Code2给我例外。 Here is the log 这是日志

The data contract type 'ScrollViewExample.Person' cannot be deserialized because the member 'properties' is not public. 数据协定类型'ScrollViewExample.Person'无法反序列化,因为成员'properties'不是公共的。 Making the member public will fix this error. 公开该成员将解决此错误。 Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. 或者,可以将其设置为内部,并在程序集中使用InternalsVisibleToAttribute属性以启用内部成员的序列化-有关更多详细信息,请参见文档。 Be aware that doing so has certain security implications. 请注意,这样做有一定的安全隐患。

The problem here is that I don't have a structure defined for the properties it can have any keys so I can't define a class for it. 这里的问题是我没有为properties定义一个结构,它可以具有任何键,因此无法为其定义类。 I'm posting this question because I have a problem and after investigating I found that I can't parse dictionary. 我发布此问题是因为我有问题 ,经过调查后发现我无法解析字典。 So I'm framing my problem into a simpler one so that you guys may give your inputs 所以我将我的问题简化为一个简单的问题,以便你们可以提供您的意见

Unfortunately DataContractJsonSerializer expects your json data as 不幸的是DataContractJsonSerializer希望您的json数据为

  {"properties":[{"Key":"Name","Value":"Valorie"},{"Key":"Month","Value":"May"},{"Key":"Year","Value":"2013"}]}

I think using Json.NET is a good idea to parse json 我认为使用Json.NET是解析json的一个好主意

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM