Search code examples
c#serializationrestsharpwebapijsonserializer

Rest Sharp request.JsonSerializer.Serialize(Myobj) Throws Null Reference Exception


I am using Rest Sharp and a small class to create a post request to a webapi When I try to serialize the object with this, var json = restRequest.JsonSerializer.Serialize(Myobj); it throws a null reference exception, not sure what I am missing here to make this work? Here's what I have so far:

public class UserAuth
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }


RestClient restClient = new RestClient("WebAddress");
RestRequest restRequest = new RestRequest("Authenticate", Method.POST);
var Myobj = new UserAuth { UserName = "MyUserName", Password = "MyPassword"};
var json = restRequest.JsonSerializer.Serialize(Myobj);

Solution

  • It looks like you are trying to use a seralizer which is on the restRequest. Are you sure that property exists? If it does it would likely be used internally and you probably can't guarantee it is there.

    You can use the Newtonsoft.Json Nuget package to deseralize your response.

    Here is a simple tutorial to get you started: https://www.newtonsoft.com/json/help/html/DeserializeObject.htm