gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:48:31 25 4
gpt4 key购买 nike

我需要反序列化以下 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());

关于C# Web Api - NUnit 测试 - Newtonsoft.Json.JsonSerializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58076651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com