How to access elements of a JArray (or iterate over them)

前端 未结 3 1255
暗喜
暗喜 2020-12-02 22:21

I have the following Json gotten from Twitter

     +      token   {[
  {
    \"trends\": [
      {
        \"name\": \"Croke Park II\",
        \"url\": \"ht         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 22:45

    There is a much simpler solution for that.
    Actually treating the items of JArray as JObject works.
    Here is an example:
    Let's say we have such array of JSON objects:

    JArray jArray = JArray.Parse(@"[
                  {
                    ""name"": ""Croke Park II"",
                    ""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
                    ""promoted_content"": null,
                    ""query"": ""%22Croke+Park+II%22"",
                    ""events"": null
                  },
                  {
                    ""name"": ""Siptu"",
                    ""url"": ""http://twitter.com/search?q=Siptu"",
                    ""promoted_content"": null,
                    ""query"": ""Siptu"",
                    ""events"": null
                  }]");
    

    To get access each item we just do the following:

    foreach (JObject item in jArray)
    {
        string name = item.GetValue("name").ToString();
        string url = item.GetValue("url").ToString();
        // ...
    }
    

提交回复
热议问题