开发者

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

开发者 https://www.devze.com 2023-01-31 01:02 出处:网络
I have an issue where if my json file looks like this { \"Numbers\": \"45387\", \"Words\": \"space buckets\"}

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 DataContract开发者_StackOverflow社区JsonSerializer(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.

0

精彩评论

暂无评论...
验证码 换一张
取 消