Deserializing JSON using System.Runtime.Serialization.Json

一个人想着一个人 提交于 2020-01-15 06:53:57

问题


I'm having issues with deserializing some json with C#.

Suppose this is a snippet of the json I'm being sent (repeated many times, but nothing else other than id/name):

[
    {
    "id":0,
    "name":"N/A"
    },
    {
        "id":1,            
        "name":"Annie"            
    },
    {
        "id":2,            
        "name":"Olaf"            
    }    
]

If the top level was named, I'd do something like

[DataContract]
public class ChampList
{
    [DataMember(Name = "SOMENAME")]
    public ElophantChamp[] ElophantChamps { get; set; }
}

[DataContract]
public class ElophantChamp
{
    [DataMember(Name = "id")]
    public int ID { get; set; }

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

}

and then deserialize it by calling this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(ChampList));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
ChampList jsonResults = objResponse as ChampList;

But in the case where there is no top level container object and I can't have blank datamember name, what do I do? I just get a null value if I leave the DataMember unnamed (i.e. leave it as just [DataMember]), which I would take to indicate that couldn't parse it correctly.

No errors are thrown and the sesponse stream is populated with exactly what I expect.

From what I can tell searching around and basic reasoning, I shouldn't be very far off from where I need to be. There's just something I'm doing wrong with handling that highest level.


回答1:


Does it work without the parent class ChampList?

DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(ElophantChamp[]));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
ElophantChamp[] jsonResults = objResponse as ElophantChamp[];


来源:https://stackoverflow.com/questions/13506542/deserializing-json-using-system-runtime-serialization-json

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