使用RestSharp调用REST API并反序列化响应

时间:2016-08-03 16:14:30

标签: c# json serialization restsharp

此代码调用REST API:

using RestSharp;
using System;

namespace NetWebclient
{
    class Program
    {
        static void Main(string[] args)
        {
            var point = new Point();
            point.x = 1;
            point.y = 2;

            var rec = new Rectangle();
            rec.point = point;
            rec.width = 100;
            rec.height = 100;

            var client = new RestClient("http://localhost.:3000");

            var request = new RestRequest("rectangle/move/100/100", Method.POST);
            request.AddJsonBody(rec);

            do
            {
                Console.WriteLine("Press any key to start the request:");
                Console.ReadKey();

                // async with deserialization
                var asyncHandle = client.ExecuteAsync<Rectangle>(request, response => {
                    Console.WriteLine(response.Content);
                    Console.WriteLine(response.Data.point);
                });                

            } while (true);            
        }
    }
}

矩形对象类定义如下:

namespace NetWebclient
{       
    public class Point 
    {
        public int x;
        public int y;

        public Point() 
        {

        }       
    }

    public class Rectangle 
    {
        public int width;
        public int height;
        public Point point;

        public Rectangle() 
        {

        }       
    }
}

当我执行请求时,这些是Fiddler记录的标题:

POST http://localhost.:3000/rectangle/ HTTP/1.1
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: RestSharp/105.2.3.0
Content-Type: application/json
Host: localhost.:3000
Content-Length: 48
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

{"width":100,"height":100,"point":{"x":1,"y":2}}

这就是回应:

HTTP/1.1 200 OK
Date: Wed, 03 Aug 2016 15:40:33 GMT
Server: Warp/3.2.6
Content-Type: application/json; charset=utf-8
Content-Length: 48

{"height":100,"width":100,"point":{"x":1,"y":2}}

当我想将响应反序列化回类型Rectangle时,会发生错误。 response.Data的类型为Rectangle,但是response.Data.width,response.Data.height或response.Data.point等所有属性都为零或null。 我错过了什么?

0 个答案:

没有答案