Skip to main content
 首页 » 编程设计

C# Web Api之NUnit 测试之Newtonsoft.Json.JsonSerializationException

2024年02月04日34soundcode

我需要反序列化以下 JSON 字符串。

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

同样的测试代码是:

[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); 
            }); 
        } 
    } 

但是当我尝试使用反序列化器时,它给出了一个异常。

Newtonsoft.Json.JsonSerializationException : Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[IMS_NL.Models.Domain]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. 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.

显示上述错误的行是--

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

帮我解决一下。提前致谢。

请您参考如下方法:

您需要创建一个对应于您的 JSON 字符串的类

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; } 
} 

然后使用 var returnData = JsonConvert.DeserializeObject<Answer>(successStatus.Data.ToString());