How would I read into a 'nested' Json file with 'DataContractJsonSerializer' in C# .NET (win7 phone)?

StackOverflow https://stackoverflow.com/questions/4477616

سؤال

I have an issue where if my json file looks like this

{ "Numbers": "45387", "Words": "space buckets"}

I can read it just fine, however if it looks like this:

{ "Main" :{ "Numbers": "45387", "Words": "space buckets"},
"Something" :{"Numbers": "12345", "Words": "Kransky"} }

I get no information back. I have no idea how to switch between Main and Something! Loading a JSON with this 'nested' information using this code,

var ser = new DataContractJsonSerializer(typeof(myInfo));

var info = (myInfo)ser.ReadObject(e.Result); 

// The class being using to hold my information

[DataContract] 
public class myInfo 
{ 
    [DataMember(Name="Numbers")] 
    public int number 
    { get; set; } 

    [DataMember(Name="Words")] 
    public string words 
    { get; set; } 
} 

Causes the class to come back empty.
I've tried adding the group name to DataContract eg. [DataContract, Name="Main"] but this still causes the classes values to be empty.
I've also tried adding "main" to the serializer overloader eg. var ser = new DataContractJsonSerializer(typeof(myInfo), "Main");
This causes an error: Expecting element 'Main' from namespace ''.. Encountered 'Element' with name 'root', namespace ''.
I'd prefer to just use the supplied json reader. I have looked into json.NET but have found the documentation to be heavy on writing json and sparse with information about reading. Surely I'm missing something simple here!

هل كانت مفيدة؟

المحلول

You could add a wrapper class:

[DataContract]
public class Wrapper
{
    [DataMember]
    public myInfo Main { get; set; }

    [DataMember]
    public myInfo Something { get; set; }
}

Now you could deserialize the JSON back to this wrapper class and use the two properties to access the values.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top