Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39988

Parse dictionary from json windows phone

I have two piece of code

Code1

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

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. Here is the log

The data contract type 'ScrollViewExample.Person' cannot be deserialized because the member 'properties' is not public. 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. 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. 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

Upvotes: 2

Views: 827

Answers (1)

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39988

Unfortunately DataContractJsonSerializer expects your json data as

  {"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

Upvotes: 1

Related Questions