Не удается десериализовать JSON из REST API (Wordpress) с помощью RestSharp

Это сводило меня с ума - я не могу десериализовать некоторые JSON, которые я получаю из общедоступного API Wordpress, чтобы получать свои сообщения. Я использую Рестшарп. Данные, которые я возвращаю, показывают сообщение в блоге, но все свойства пусты. Я даже использовал Json2CSharp для моделирования моего класса «Post» после того, что было возвращено.

Вот мой JSON:

{
   "found":1,
   "posts":[
      {
         "ID":2,
         "site_ID":89749867,
         "author":{
            "ID":2988648,
            "login":"loginname",
            "email":false,
            "name":"loginname",
            "nice_name":"loginname",
            "URL":"",
            "avatar_URL":"https:\/\/2.gravatar.com\/avatar\/e78ee2e2f7bb75a8bc5339a6bd20194e?s=96&d=identicon&r=G",
            "profile_URL":"http:\/\/en.gravatar.com\/loginname",
            "site_ID":2918427
         },
         "date":"2015-04-20T18:16:18+00:00",
         "modified":"2015-04-20T18:18:20+00:00",
         "title":"Hello world!",
         "URL":"https:\/\/myblog.wordpress.com\/2015\/04\/20\/hello-world\/",
         "short_URL":"http:\/\/wp.me\/p64A2v-2",
         "content":"<p><a href=\"https:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png\"><img class=\"alignnone size-medium wp-image-3\" src=\"https:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png?w=300&#038;h=180\" alt=\"Left Shark\" width=\"300\" height=\"180\" \/><\/a><\/p>\n<p>This is your very first post. Click the Edit link to modify or delete it, or <a title=\"Direct link to Add New Post in your Dashboard\" href=\"https:\/\/wordpress.com\/post\">start a new post<\/a>. If you like, use this post to tell readers why you started this blog and what you plan to do with it.<\/p>\n<p>Happy blogging!<\/p>\n",
         "excerpt":"<p>This is your very first post. Click the Edit link to modify or delete it, or start a new post. If you like, use this post to tell readers why you started this blog and what you plan to do with it. Happy blogging!<\/p>\n",
         "slug":"hello-world",
         "guid":"http:\/\/myblog.wordpress.com\/?p=1",
         "status":"publish",
         "sticky":false,
         "password":"",
         "parent":false,
         "type":"post",
         "discussion":{
            "comments_open":true,
            "comment_status":"open",
            "pings_open":true,
            "ping_status":"open",
            "comment_count":0
         },
         "likes_enabled":true,
         "sharing_enabled":true,
         "like_count":0,
         "i_like":0,
         "is_reblogged":0,
         "is_following":0,
         "global_ID":"7a5ad608c4e80f7c2463eead8d34f435",
         "featured_image":"https:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png",
         "post_thumbnail":{
            "ID":3,
            "URL":"https:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png",
            "guid":"http:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png",
            "mime_type":"image\/png",
            "width":620,
            "height":372
         },
         "format":"standard",
         "geo":false,
         "menu_order":0,
         "page_template":"",
         "publicize_URLs":[

         ],
         "tags":{

         },
         "categories":{
            "Uncategorized":{
               "ID":1,
               "name":"Uncategorized",
               "slug":"uncategorized",
               "description":"",
               "post_count":1,
               "parent":0,
               "meta":{
                  "links":{
                     "self":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/categories\/slug:uncategorized",
                     "help":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/categories\/slug:uncategorized\/help",
                     "site":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867"
                  }
               }
            }
         },
         "attachments":{
            "3":{
               "ID":3,
               "URL":"https:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png",
               "guid":"http:\/\/myblog.files.wordpress.com\/2015\/04\/left_shark_5x3.png",
               "date":"2015-04-20T18:17:33+00:00",
               "post_ID":2,
               "file":"left_shark_5x3.png",
               "mime_type":"image\/png",
               "extension":"png",
               "title":"Left Shark",
               "caption":"",
               "description":"",
               "alt":"Left Shark",
               "thumbnails":{

               },
               "height":372,
               "width":620,
               "exif":{
                  "aperture":0,
                  "credit":"",
                  "camera":"",
                  "caption":"",
                  "created_timestamp":0,
                  "copyright":"",
                  "focal_length":0,
                  "iso":0,
                  "shutter_speed":0,
                  "title":"",
                  "orientation":0
               },
               "meta":{
                  "links":{
                     "self":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/media\/3",
                     "help":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/media\/3\/help",
                     "site":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867",
                     "parent":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/posts\/2"
                  }
               }
            }
         },
         "attachment_count":1,
         "metadata":[
            {
               "id":"9",
               "key":"_thumbnail_id",
               "value":"3"
            }
         ],
         "meta":{
            "links":{
               "self":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/posts\/2",
               "help":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/posts\/2\/help",
               "site":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867",
               "replies":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/posts\/2\/replies\/",
               "likes":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/89749867\/posts\/2\/likes\/"
            }
         },
         "capabilities":{
            "publish_post":false,
            "delete_post":false,
            "edit_post":false
         }
      }
   ]
}

Вот мой класс (с некоторыми свойствами, закомментированными, поэтому мне не пришлось их создавать:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace thenickwilson_SPA_NEW.Models
{
    public class Post
    {
        public int ID { get; set; }
        public int site_ID { get; set; }
        //public Author author { get; set; }
        public string date { get; set; }
        public string modified { get; set; }
        public string title { get; set; }
        public string URL { get; set; }
        public string short_URL { get; set; }
        public string content { get; set; }
        public string excerpt { get; set; }
        public string slug { get; set; }
        public string guid { get; set; }
        public string status { get; set; }
        public bool sticky { get; set; }
        public string password { get; set; }
        public bool parent { get; set; }
        public string type { get; set; }
        //public Discussion discussion { get; set; }
        public bool likes_enabled { get; set; }
        public bool sharing_enabled { get; set; }
        public int like_count { get; set; }
        public int i_like { get; set; }
        public int is_reblogged { get; set; }
        public int is_following { get; set; }
        public string global_ID { get; set; }
        public string featured_image { get; set; }
        //public PostThumbnail post_thumbnail { get; set; }
        public string format { get; set; }
        public bool geo { get; set; }
        public int menu_order { get; set; }
        public string page_template { get; set; }
        public List<object> publicize_URLs { get; set; }
        //public Tags tags { get; set; }
        //public Categories categories { get; set; }
        //public Attachments attachments { get; set; }
        public int attachment_count { get; set; }
        //public List<Metadata> metadata { get; set; }
        //public Meta3 meta { get; set; }
        //public Capabilities capabilities { get; set; }
    }
}

И вот остальная часть моего кода:

[ResponseType(typeof(Post))]
        public IHttpActionResult Get()
        {
            var client = new RestClient("http://public-api.wordpress.com/rest/v1.1/");
            var request = new RestRequest("sites/{id}/posts", Method.GET);
            request.AddUrlSegment("id", "myblog.wordpress.com");
            request.RequestFormat = DataFormat.Json;

            var response = client.Execute<List<Post>>(request);

            return this.Ok(response);
        }

У меня есть ощущение, что это связано с тем, что API возвращает «найденный» элемент, а также «сообщения», но я не уверен. Любая помощь будет принята с благодарностью.


person the-nick-wilson    schedule 20.04.2015    source источник


Ответы (1)


Вы получаете массив или список сообщений, завернутый в объект-контейнер, поэтому попробуйте следующее:

  public class MyContainer
  { 
       public List<Post> posts {get;set;}
  }

А также:

  var response = client.Execute<MyContainer>(request);

Вы можете просмотреть свой десериализованный json здесь: http://jsonviewer.stack.hu/

person AiApaec    schedule 20.04.2015
comment
Это была именно проблема. Спасибо. Является ли это общим для REST API? - person the-nick-wilson; 21.04.2015
comment
Я не думаю, зависит от того, что возвращает сервер. У меня есть спокойный сервис, возвращающий список объектов без его упаковки. К счастью, существуют такие инструменты, как этот просмотрщик json. Ну, json ясен, в контейнере также есть найденное поле. - person AiApaec; 21.04.2015