【发布时间】:2017-03-02 07:59:30
【问题描述】:
我正在使用 c# 在我的 asp.net mvc 项目中使用域名的促销定价 api。我想获得特定产品密钥的经销商价格,例如“dotgold”。在这个 Api 对象名称是动态的,如 59,58 等等。我怎样才能做到这一点。以下是该 api 的 json 对象...
{
"59": {
"customerprice": "528.00",
"timestamp": "2017-02-10 13:59:16.711147+00",
"actiontype": "addnewdomain",
"resellerpricecurrencysymbol": "INR",
"resellerpricetwo": "748.00",
"isactive": "true",
"starttime": "1486393372",
"productkey": "dotjetzt",
"creationdt": "1486735157",
"promoid": "13333",
"serviceprovidersellingcurrency": "INR",
"istrickleallow": "true",
"resellerpriceone": "489.50",
"resellerid": "683272",
"barrierprice": "680.0",
"period": "1",
"endtime": "1491004799",
"resellerprice": "445.0"
},
"58": {
"customerprice": "302.50",
"timestamp": "2017-02-10 13:59:16.711147+00",
"actiontype": "addnewdomain",
"resellerpricecurrencysymbol": "INR",
"resellerpricetwo": "451.00",
"isactive": "true",
"starttime": "1486393234",
"productkey": "dotgold",
"creationdt": "1486735157",
"promoid": "13332",
"serviceprovidersellingcurrency": "INR",
"istrickleallow": "true",
"resellerpriceone": "264.00",
"resellerid": "683272",
"barrierprice": "410.0",
"period": "1",
"endtime": "1491004799",
"resellerprice": "240.0"
}
}
下面是反序列化 json 对象的代码
string redirect = @"https://test.httpapi.com/api/resellers/promo-details.json?auth-userid=xxxx&api-key=xxxxxxxxxxxx";
string html;
var headers = new System.Net.WebHeaderCollection();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(redirect);
request.AutomaticDecompression = DecompressionMethods.GZip;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
var stuff = JObject.Parse(html2);
【问题讨论】:
-
如果不知道您是如何反序列化 JSON 或 JSON 是什么样子,真的很难为您提供帮助。请提供minimal reproducible example - 请注意这不是特定于 ASP.NET 的,因此控制台应用程序将更容易演示。
-
我已经给了json对象
-
但是到目前为止,您还没有为您尝试过的内容提供任何代码,而且您提供的 JSON 远非最小 - 我们不需要为每个值查看 18 个属性,只需足以制作有代表性的样本。
-
现在有一些代码,但它最初是糟糕格式的 - 请在点击提交之前使用预览来确保帖子看起来像您想要的样子。现在,您提供的大部分代码都是关于如何将 JSON 作为字符串获取,这并不是非常重要 - 但至少您已经证明您正在使用
JObject.Parse。现在您可以只遍历JObject中的所有属性,或者您可以反序列化为Dictionary<int, SomeClass>。 -
如果您不想为 JSON 创建具体的类类型,那么您可以使用 ExpandoObject 并将其视为动态的。但是,如果您可以创建一个类并管理您想要拥有的属性,那就太好了。然后使用 Json.NET 的 JsonConvert.Deserialize 方法对它进行相应的反序列化以键入 Dictionary
。