使用System.Runtime.Serialization.Json反序列化JSON [英] Deserializing JSON using System.Runtime.Serialization.Json

查看:264
本文介绍了使用System.Runtime.Serialization.Json反序列化JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用C#反序列化某些json时遇到问题.

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

假设这是我正在发送的json的代码段(重复了很多次,但除了id/name之外没有其他):

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;

但是在没有顶级容器对象并且我不能使用空白数据成员名称的情况下,该怎么办?如果我不给DataMember命名(即仅将其命名为[DataMember]),我只会得到一个空值,这将表明无法正确解析它.

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.

推荐答案

在没有父类ChampList的情况下可以正常工作吗?

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[];

这篇关于使用System.Runtime.Serialization.Json反序列化JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆