Simplify looking up nested Json values with Json.NET

♀尐吖头ヾ 提交于 2019-12-12 03:07:09

问题


I use the Facebook's graph Api to get posts from a Facebook page I administer. To get a url to the full size picture of a post I included the "attachments" field. the JSon obtained is as follows:

{
  "data": [
    {
      "message": "Using Facebook's Graph Api to get Testdrive's news from the Facebook page on to the website. So this post will be visible in a minute at the website as well. Cool!",
      "link": "https://www.facebook.com/TestdriveDressage/photos/a.493612667417831.1073741827.493607594085005/681741335271629/?type=1&relevant_count=1",
      "picture": "https://scontent-b.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/s130x130/10394069_681741335271629_2094079936902591674_n.png?oh=85676b5ec301e78bd15e2cabde9b8f8f&oe=5561C419",
      "id": "493607594085005_681741408604955",
      "created_time": "2015-02-03T15:58:54+0000",
      "attachments": {
        "data": [
          {
            "description": "Using Facebook's Graph Api to get Testdrive's news from the Facebook page on to the website. So this post will be visible in a minute at the website as well. Cool!",
            "media": {
              "image": {
                "height": 666,
                "src": "https://scontent-b.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/s720x720/10394069_681741335271629_2094079936902591674_n.png?oh=ac58799007b9b909ebc9f0ca762fd6c6&oe=554BD8A3",
                "width": 720
              }
            },
            "target": {
              "id": "681741335271629",
              "url": "https://www.facebook.com/TestdriveDressage/photos/a.493612667417831.1073741827.493607594085005/681741335271629/?type=1"
            },
            "title": "Timeline Photos",
            "type": "photo",
            "url": "https://www.facebook.com/TestdriveDressage/photos/a.493612667417831.1073741827.493607594085005/681741335271629/?type=1"
          }
        ]
      }
    }, ... next "post"

Now I use Json.Net in c£ like this to get post.data.attachments.media.image.src:

FacebookClient fbClient = new FacebookClient(HttpContext.Current.Session[SessionFacebookAccessToken].ToString());
                    JObject posts = JObject.Parse(fbClient.Get(String.Format("/{0}/posts?fields=message,picture,link,attachments", FacebookPageId)).ToString());
                    JArray postItems = (JArray)posts["data"];
                    List<NewsItem> newsItems = new List<NewsItem>();

                    NewsItem ni;

                    foreach (JToken item in postItems.Where(item => item["message"] != null))
                    {
                        ni = new NewsItem { Message = item.Value<String>("message"), DateTimeCreation = item.Value<DateTime?>("created_time"), Link = item.Value<String>("link"), Thumbnail = item.Value<String>("picture") };

                        JToken attachments = item["attachments"];

                        // "Browse" attachments node for possible links to larger image...
                        if (attachments != null)
                        {
                            JToken attachmentsData = attachments["data"];

                            if (attachmentsData != null)
                            {
                                JToken attachmentsArray = attachments["data"];

                                if (attachmentsArray != null)
                                {
                                    JToken media = attachmentsArray[0];

                                    if (media != null)
                                    {
                                        JToken media2 = media["media"];

                                        if (media2 != null)
                                        {
                                            JToken image = media2["image"];

                                            if (image != null)
                                            {
                                                ni.Image = image.Value<String>("src");
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        newsItems.Add(ni);
                    }

Is there anyway I can simplify this?

It feels a bit odd and I'm not so happy with it...I tried already item["attachments"]["data"]["media"]["image"]["src"] but doesn't work because there's an array at "data" I guess

Any advice or explanation is appreciated.


回答1:


Try using SelectToken(). You can specify a path to the value you want. If any item along the path is null, the whole expression will be null. This can greatly simplify your code. I've added a fiddle to demonstrate.

string url = (string)item.SelectToken("attachments.data[0].media.image.src");

Fiddle: https://dotnetfiddle.net/YL6t5c



来源:https://stackoverflow.com/questions/28319242/simplify-looking-up-nested-json-values-with-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!