在C#中解析JSON [英] Parsing JSON in C#
问题描述
我从RESTful API以JSON对象的形式返回响应.通常,当密钥已知时,我可以很好地解析它.例如,我创建一个User
类,如下所示:
I am getting a response back from a RESTful API in the form of a JSON object. Normally, I can parse this just fine when the keys are known. For instance, I create a User
class like this:
[DataContract]
public class User
{
[DataMember]
public string id { get; set; }
[DataMember]
public string name { get; set; }
[DataMember]
public string email { get; set; }
}
我所要做的就是将响应读取到我的JSON解串器中,并告诉其输出是< User>我很好.在发出其他请求(例如销售数据)时,这不足.我得到的回复是这样的:
All I have to do is pull read the response into my JSON deserializer and tell it the output is a <User> and I'm good to go. This falls short when making other requests, such as sales data. The response I get back is something like this:
{
"2010-11-24": {
"country": null,
"iso": null,
"product": null,
"downloads": 39,
"net_downloads": 38,
"updates": 6,
"revenue": "19.02",
"returns": 1,
"gift_redemptions": 0,
"promos": 0
},
"2010-11-25": {
"country": null,
"iso": null,
"product": null,
"downloads": 63,
"net_downloads": 63,
"updates": 6,
"revenue": "37.00",
"returns": 0,
"gift_redemptions": 0,
"promos": 0
}
}
如果我可以将此类建模为[DataContract]
,那我会很高兴,但是由于第一个键是日期,因此我无法对此进行硬编码.
If I could model this class as a [DataContract]
then I'd be golden, but since the first key is a date, I can't hard code that.
是否存在一个可以接受这种响应并将其转换为强类型C#类的JSON库?
Is there a JSON library out there that can take this kind of response and turn it into a strongly-typed C# class?
为了记录,我使用的是此SO问题中使用的JSONHelper.
For the record, I'm using the JSONHelper used in this SO question.
推荐答案
JSON.NET 被认为是最好/最快/最稳定的JSON C#库.我已经用过了,它可以像宣传的那样工作.
JSON.NET is recognized as the best/fastest/most stable JSON C# library. I've used it, it works as advertised.
这篇关于在C#中解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!