简体   繁体   English

如何在c#中只读取HTTP Response body中的特定部分?

[英]How to read only a specific part from HTTP Response body in c#?

I need only the "points": 300 from the below response body.我只需要以下响应正文中的“点数”:300。

Here is the body:这是正文:

{
  "channel": "abcd",
  "username": "fgh",
  "points": 300,
  "pointsAlltime": 0,
  "watchtime": 0,
  "rank": 1
}

The Code:代码:

public async int get_points(string user){
 var client = new HttpClient();
 var request = new HttpRequestMessage
 {
    Method = HttpMethod.Get,
    RequestUri = new 
    Uri("https://api.streamelements.com/kappa/v2/points/abcd/fgh"),
    Headers =
    {
        { "Accept", "application/json" },
        { "Authorization", "Bearer 123" },
    },
  };
 using (var response = await client.SendAsync(request))
 {
    response.EnsureSuccessStatusCode();
    var body = await response.Content.ReadAsStringAsync();
    Console.WriteLine(body);
 }
}

I need only the points value.我只需要点值。 - 300 - 300

You need to deserialize your string response into JSON and with the help of the property name you need to extract the points value.您需要将字符串响应反序列化为 JSON,并借助属性名称提取points值。

Using JObject.Parse(String) ,使用JObject.Parse(String)

using (var response = await client.SendAsync(request))
{
    response.EnsureSuccessStatusCode();
    var result = await response.Content.ReadAsStringAsync();

    JObject jObj = JObject.Parse(result);
    Console.WriteLine(jObj["points"]);
}

You can also try the native .NET approach introduced in .NET 6+ versions ie JsonNode.Parse() ,您还可以尝试在 .NET 6+ 版本中引入的本机 .NET 方法,即JsonNode.Parse()

var jNode = JsonNode.Parse(result);
Console.WriteLine(jNode["points"]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM