简体   繁体   English

需要帮助从JSON键/值对获取特定值

[英]Need Help getting a specific value from a JSON key/value pair

I am pulling data from a 3rd party API and have myself some code that looks like this... 我正在从第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());
        }
    }
}

Instead of displaying all the information in the object as a string, I would like to take a specific value from that object, store it into a variable, and use that variable in another HTTPRequest. 与其将对象中的所有信息显示为字符串,不如从该对象中获取特定值,将其存储到变量中,然后在另一个HTTPRequest中使用该变量。

The output I am getting looks like this... 我得到的输出看起来像这样...

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

I would like to specifically focus on the membershipId key/value. 我想特别关注于MembershipId键/值。

var membershipId = (string)item.Response[0].membershipId;

I think what you're looking to do can be found in Newtonsoft's Documentation here 我想您可以在此处的Newtonsoft's Documentation中找到您想做的事情

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

In this example they are using linq to find specific things on the Object, but you can also For Each through each element within your return object. 在此示例中,他们使用linq查找对象上的特定内容,但是您也可以通过返回对象内的每个元素来使用For Each。

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

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