简体   繁体   中英

C# Web Api - NUnit Testing - Newtonsoft.Json.JsonSerializationException

I need to deserialize the following JSON string.

{"status":"success","data":[{"id":4,"domainTitle":"Java","isDeleted":true},{"id":5,"domainTitle":"PHP","isDeleted":true},{"id":6,"domainTitle":"Angular","isDeleted":true}]}

The test code for the same is:

[Test]
    public async Task TestGetDeletedDomainsAsync_UserDomains_StatusCodeOK()
    {
        using (var adminController = new AdminController(_adminService.Object))
        {
            //act
            var response = _adminController.GetDeletedDomainsAsync();
            var successStatus = await response.Content.ReadAsAsync<SuccessStatus>();
            var returnData = JsonConvert.DeserializeObject<List<Domain>>(successStatus.Data.ToString());
            // assert
            Assert.Multiple(() =>
            {
                Assert.That(response, Is.TypeOf<HttpResponseMessage>());
                Assert.That(returnData, Is.TypeOf<List<Domain>>());
                Assert.AreEqual(response.StatusCode, HttpStatusCode.OK);
                Assert.IsNotNull(successStatus);
                Assert.AreEqual("success", successStatus.Status);
                Assert.IsNotNull(returnData);
                //checking if same object goes to service and also if that service is called once
                _adminService.Verify(s => s.GetDeletedDomains(), Times.Once);
            });
        }
    }

But when I try using the de-serializer, it gives an exception.

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[IMS_NL.Models.Domain]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

The line that displays the above error is --

var returnData = JsonConvert.DeserializeObject<List<Domain>>(successStatus.Data.ToString());

Help me with a solution. Thanks in advance.

You need to make a class which correspond your JSON string

public class Answer
{
    public string Status { get; set; }
    public List<Domain> Data { get; set; }
}

public class Domain
{
    public int Id { get; set; }
    public string DomainTitle { get; set; }
    public bool IsDeleted { get; set; }
}

Then use var returnData = JsonConvert.DeserializeObject<Answer>(successStatus.Data.ToString());

I think that your problem resides in the declaration of Domain class. You should define the below classes, according to the JSON you have posted:

public class Domain
{
    public int id { get; set; }
    public string domainTitle { get; set; }
    public bool isDeleted { get; set; }
}

public class Result
{
    public string status { get; set; }
    public List<Domain> data { get; set; }
}


var returnData = JsonConvert.DeserializeObject<Result>(...);

You should replace the ... with the JSON you get from that you call.

Optionally, you could rename the above classes as you think that would be more suitable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM