刚开始重新玩 C#,我无法克服这个问题。
我有以下 JSON 内容:
{
"type": "success",
"picks": [
{
"aftermarket": {
"domain": "ao38t8u4h.com",
"fast_transfer": false,
"price": 0,
"status": "notfound",
"type": "",
"username": ""
},
"domain": "ao38t8u4h.com",
"info": "",
"priority": 1,
"status": {
"available": true,
"lookupType": "EPP",
"name": "ao38t8u4h.com",
"premium": false
},
"tld": "com",
"type": "domain"
},
{
"aftermarket": {
"domain": "ao38t8u4h.net",
"fast_transfer": false,
"price": 0,
"status": "notfound",
"type": "",
"username": ""
},
"domain": "ao38t8u4h.net",
"info": "",
"priority": 2,
"status": {
"available": true,
"lookupType": "EPP",
"name": "ao38t8u4h.net",
"premium": false
},
"tld": "net",
"type": "domain"
},
{
"aftermarket": {
"domain": "ao38t8u4h.dev",
"fast_transfer": false,
"price": 0,
"status": "notfound",
"type": "",
"username": ""
},
"domain": "ao38t8u4h.dev",
"info": "",
"priority": 3,
"status": {
"available": true,
"lookupType": "EPP",
"name": "ao38t8u4h.dev",
"premium": false
},
"tld": "dev",
"type": "domain"
},
{
"aftermarket": {
"domain": "ao38t8u4h.ai",
"fast_transfer": false,
"price": 0,
"status": "notfound",
"type": "",
"username": ""
},
"domain": "ao38t8u4h.ai",
"info": "",
"priority": 4,
"status": {
"available": true,
"lookupType": "EPP",
"name": "ao38t8u4h.ai",
"premium": false
},
"tld": "ai",
"type": "domain"
},
{
"aftermarket": {
"domain": "ao38t8u4h.org",
"fast_transfer": false,
"price": 0,
"status": "notfound",
"type": "",
"username": ""
},
"domain": "ao38t8u4h.org",
"info": "",
"priority": 5,
"status": {
"available": true,
"lookupType": "EPP",
"name": "ao38t8u4h.org",
"premium": false
},
"tld": "org",
"type": "domain"
}
]
}
我想做的是获取 ["picks"][0]["status"]["premium"]
中的值。我在 Python 中所做的是获取响应,然后简单地 print(var["picks"][0]["status"]["premium"])
打印值;但是,我不知道如何在 C# 中完成此操作。
我使用的代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Http;
using Newtonsoft.Json;
namespace testing
{
class Program
{
private static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
try
{
string domain = "ao38t8u4h";
string url = "https://rtb.namecheapapi.com/api/picks/" + domain;
string responseBody = await client.GetStringAsync(url);
var json = JsonConvert.DeserializeObject(responseBody);
Console.WriteLine(json);
Console.ReadLine();
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
Console.ReadLine();
}
}
}
}
最佳答案
如果您使用 JTokens
,Json.Net 支持您习惯的语法.
JToken jt = JToken.Parse(responseBody);
Console.WriteLine(jt["picks"][0]["status"]["premium"]);
fiddle :https://dotnetfiddle.net/BssMHq
关于c# - 从 JSON 响应打印特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57956051/