c# - 如何解析 Json 响应并存储一些属性
问题描述
我目前正在尝试解析来自此链接的响应:https ://api.ote-godaddy.com/v1/domains 。
现在在我的程序中,我应该得到这种类型的响应:
[
{
"createdAt": "2015-06-15T13:10:43.000Z",
"domain": "000.biz",
"domainId": 1002111,
"expirationProtected": false,
"expires": "2016-06-14T23:59:59.000Z",
"exposeWhois": false,
"holdRegistrar": false,
"locked": true,
"nameServers": null,
"privacy": false,
"renewAuto": true,
"renewable": false,
"status": "TRANSFERRED_OUT",
"transferAwayEligibleAt": "2016-07-29T23:59:59.000Z",
"transferProtected": false
},
{
"createdAt": "2015-06-15T13:10:43.000Z",
"domain": "000.biz",
"domainId": 1002111,
"expirationProtected": false,
"expires": "2016-06-14T23:59:59.000Z",
"exposeWhois": false,
"holdRegistrar": false,
"locked": true,
"nameServers": null,
"privacy": false,
"renewAuto": true,
"renewable": false,
"status": "TRANSFERRED_OUT",
"transferAwayEligibleAt": "2016-07-29T23:59:59.000Z",
"transferProtected": false
}
]
我需要解析它以获取每个 domain
属性并编写它。这就是我想出的:
const string WEBSERVICE_URL = "https://api.ote-godaddy.com/v1/domains?statuses=&includes=";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.Timeout = 12000;
webRequest.ContentType = "application/json";
webRequest.Headers.Add("Authorization", "sso-key " + api_key + ":" + api_secret);
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
if (jsonResponse == "[]")
{
Console.WriteLine("No domains found");
bad = +1;
}
else
{
JArray jo = JArray.Parse(jsonResponse);
hit = +1;
string hit_txt = "";
hit_txt = api_key + ":" + api_secret + "=" + jo[]["domain"];
Console.WriteLine(hit_txt);
using (StreamWriter writetext = new StreamWriter("hit.txt"))
{
writetext.WriteLine(hit_txt);
}
}
}
}
}
}
(不要担心其他变量,如api_key
,一切正常)
不幸的是,我收到了这个错误:
Newtonsoft.Json.JsonReaderException:从 JsonReader 读取 JObject 时出错。当前 JsonReader 项不是对象:StartArray。路径 '',> 第 1 行,位置 1。
解决方案
在给定的场景中,可以使用以下方式选择来自 Json 的特定值JArray
:
JArray jo = JArray.Parse(jsonResponse);
//Get all "domain" elements from the Json
var domainNames = string.Join(", ", jo
.Select(jt => jt["domain"])
.ToList());
//Then use this comma separated "domainNames" in the string
string hit_txt = "";
hit_txt = api_key + ":" + api_secret + "=" + domainNames;
如果需要获取该元素的集合,请不使用string.Join
as:
var domainNames = jo
.Select(jt => jt["domain"])
.ToList();
该系列可以在任何地方进一步使用。
推荐阅读
- vue.js - 升级到 Vue 3 并将 Vue 实例化更新为 createApp 后,webpack 构建失败并出现 Module not found: Error: Can't resolve 'vue'
- python - 如何在 R 或 Python 中以高斯步长对圆上的随机游走进行采样?
- python - 对字典进行分组和排序以及添加键值
- java - 如何从 RequestBody 中排除字段 - Swagger
- java - 围绕建议和进行呼叫:aspectJ,它是如何工作的?
- http-headers - 配置 HAProxy 以拒绝/拒绝包含多个同名 HTTP 标头的请求
- angular - 无法将服务注入 Angular Provider UseFactory
- vba - 我创建的 FSO 文本文件不会关闭,并且损坏了我的应用程序
- html - 图像采用所有可用高度并将兄弟元素踢出父级
- npm - 更新 package.json 中的次要版本