使用RestSharp反序列化JSON响应导致空对象

时间:2018-11-27 12:53:41

标签: c# json rest api restsharp

我试图使用RestSharp使用REST API并反序列化到我的User类。

这是我的JSON响应:

   [
      {
        "AdName": "sample string 1",
        "Email": "sample string 2",
        "Name": "sample string 3"
      },
      {
        "AdName": "sample string 1",
        "Email": "sample string 2",
        "Name": "sample string 3"
      }
    ]

这是API客户端:

public class SamTApi
{
    const string BaseUrl = "http://localhost:8097/SamT_WebApi/api/User";


    public T Execute<T>(RestRequest request) where T : new()
    {
        var client = new RestClient();
        client.AddHandler("application/json", new JsonDeserializer());
        client.BaseUrl = new Uri(BaseUrl);

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

        return response.Data;
    }

    public List<User> GetUser()
    {
        var request = new RestRequest(Method.GET);
        request.RequestFormat = DataFormat.Json;
        return Execute<List<User>>(request);
    }
}

这是我的用户类:

public class User
{
    public string AdName { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
}

public class UserResponse
{
    public User User { get; set; }
}

所以当我尝试断言时:

var api = new SamTApi();
var users = api.GetUser();
Assert.IsNotNull(users, "users != null");

它导致用户= null。我不确定我缺少什么。

1 个答案:

答案 0 :(得分:1)

使用Newtonsoft Json nuget软件包。安装后,只需致电:

var destinationObject = JsonConvert.DeserializeObject<DestinationClass>(json);