如何从响应中读取特定值

时间:2019-08-21 12:07:53

标签: c# api

这是我用于文档https://lichess.org/api#operation/player的页面 我想获取玩家的用户名,等级和标题。 我的代码。

public class Player {
public string username;
public double rating;
public string title;
}

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://lichess.org/");
HttpResponseMessage response = client.GetAsync("player/top/200/bullet").Result;

我在这里得到回应,但是我不知道如何仅获取所需的属性并将其存储在玩家列表中。

2 个答案:

答案 0 :(得分:1)

与您讨论此问题后,发现您收到的响应是HTML字符串,因此您需要以不同的方式处理这种情况。我正在处理您在评论中发布的HTML,并且能够使用here来解析字符串HTML Agility Pack。您也可以从Nuget Package Manager中的Visual Studio下载此包。

我为您提供了一个我尝试过的解析过程的非常基本的示例:

public class ProcessHtml()
{
    List<Player> playersList = new List<Player>();

    //Get your HTML loaded from a URL. Giving me SSL exceptions so took a different route
    //var url = "https://lichess.org/player/top/200/bullet";
    //var web = new HtmlWeb();
    //var doc = web.Load(url);

    //Get your HTML loaded as a file in my case
    var doc = new HtmlDocument();
    doc.Load("C:\\Users\\Rahul\\Downloads\\CkBsZtvf.html", Encoding.UTF8);

    foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//tbody"))
    {
        foreach (HtmlNode row in table.SelectNodes("tr"))
        {
            int i = 0;
            Player player = new Player();
            //Since there are 4 rounds per tr, hence get only what is required based on loop condition
            foreach (HtmlNode cell in row.SelectNodes("th|td"))
            {                      
                if(i==1)
                {
                    player.username = cell.InnerText;
                }
                if(i==2)
                {
                    player.rating = Convert.ToDouble(cell.InnerText);
                }
                if(i==3)
                {
                    player.title = cell.InnerText;
                }                                              
                i++;
            }
            playersList.Add(player);
        }
    }

    var finalplayerListCopy = playersList;  
}

public class Player 
{
  public string username;
  public double rating;
  public string title;
}

运行此命令后,您的finalplayerListCopy的计数为200,示例数据如下:

enter image description here

很显然,您将不得不处理数据并根据需要对其进行定制。希望这对您有所帮助。

干杯!

答案 1 :(得分:0)

我从documentation读到的内容

 //this is how i store my images
if($request->hasFile('photo')){
    $pub->photo = $request->photo->store('images');
  }
 // this is my filesystemes config
    'local' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('image'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],