使用System.Runtime.Serialization.Json反序列化JSON

编程入门 行业动态 更新时间:2024-10-22 08:28:01
本文介绍了使用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

本文发布于:2023-11-10 02:23:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574082.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列化   Runtime   System   Serialization   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!