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

给你一囗甜甜゛ 提交于 2019-12-10 20:02:52

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/4477616/how-would-i-read-into-a-nested-json-file-with-datacontractjsonserializer-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!