【问题标题】:Need Help getting a specific value from a JSON key/value pair需要帮助从 JSON 键/值对获取特定值
【发布时间】:2016-04-19 18:10:41
【问题描述】:

我正在从第 3 方 API 中提取数据,并且我自己有一些看起来像这样的代码...

public partial class Form1 : Form
{
    int playSystem = 2;
    string playID = "";

    public Form1()
    {
        InitializeComponent();
    }

    private void xBox_CheckedChanged(object sender, EventArgs e)
    {
        playSystem = 1;
    }

    public void playstation_CheckedChanged(object sender, EventArgs e)
    {
        playSystem = 2;
    }

    private async void searchButton_Click(object sender, EventArgs e)
    {
        statDisplay.Clear();

        var userName = nameBox.Text;

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("X-API-KEY", "xxxxxxxxxxxxxxxx");

            var response = await client.GetAsync("https://bungie.net/platform/Destiny/SearchDestinyPlayer/" + playSystem + "/" + userName);
            var content = await response.Content.ReadAsStringAsync();
            dynamic item = Newtonsoft.Json.JsonConvert.DeserializeObject(content);

            statDisplay.AppendText(item.ToString());
        }
    }
}

我不想将对象中的所有信息显示为字符串,而是从该对象中获取一个特定值,将其存储到一个变量中,然后在另一个 HTTPRequest 中使用该变量。

我得到的输出看起来像这样......

{
  "Response": [
    {
      "iconPath": "/img/theme/destiny/icons/icon_psn.png",
      "membershipType": 2,
      "membershipId": "01234567890",
      "displayName": "xxxxxxxxxx"
    }
  ],
  "ErrorCode": 1,
  "ThrottleSeconds": 0,
  "ErrorStatus": "Success",
  "Message": "Ok",
  "MessageData": {}
}

我想特别关注membershipId 键/值。

【问题讨论】:

标签: c# json httprequest


【解决方案1】:
var membershipId = (string)item.Response[0].membershipId;

【讨论】:

    【解决方案2】:

    我认为您可以在此处的 Newtonsoft 文档中找到您要执行的操作

    http://www.newtonsoft.com/json/help/html/LINQtoJSON.htm

    在此示例中,他们使用 linq 查找对象上的特定内容,但您也可以通过返回对象中的每个元素进行 For Each。

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多