【问题标题】:Deserializing JSON using System.Runtime.Serialization.Json使用 System.Runtime.Serialization.Json 反序列化 JSON
【发布时间】:2012-11-22 05:44:42
【问题描述】:

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

假设这是我正在发送的 json 的 sn-p(重复多次,但除了 id/name 没有别的):

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

如果顶层被命名,我会做类似的事情

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

}

然后通过调用它来反序列化它:

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]),我只会得到一个空值,这表明无法正确解析它。

不会引发任何错误,并且 sesponse 流完全符合我的预期。

根据我所知道的搜索和基本推理,我应该离我需要去的地方不远。只是我在处理最高级别时做错了。

【问题讨论】:

    标签: c# json deserialization datacontractjsonserializer


    【解决方案1】:

    没有父类 ChampList 是否可以工作?

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

    【讨论】:

    • 是的,完美。我试过了,但没有意识到我可以这样做 (typeof(ElopantChamp[]) 并且只尝试过 typeof(ElopantChamp) (失败)。
    猜你喜欢
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 2012-09-05
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多