完整错误: InvalidOperationException:无法获取字符串形式的标记类型“Number”的值。 System.Text.Json.Utf8JsonReader.GetString()
JsonException:JSON 值无法转换为 System.String。路径:$[0].status |行号: 0 |字节位置内联:197。 System.Text.Json.ThrowHelper.ReThrowWithPath(参考 ReadStack 状态,参考 Utf8JsonReader 阅读器,异常 ex)
我有一个 MVC 项目正在尝试使用正常工作的 Web API。现在,有
HouseController.cs
using Microsoft.AspNetCore.Mvc;
using Task3.Controllers.Services;
namespace Task3.Controllers;
public class HouseController : Controller
{
private readonly IHouseService _service;
public HouseController(IHouseService service)
{
_service = service ?? throw new ArgumentNullException(nameof(service));
}
public async Task<IActionResult> Index()
{
var houses = await _service.Find();
return View(houses);
}
}
即调用接口中的
Find()
方法IHouseService
using Task3.Models;
namespace Task3.Controllers.Services
{
public interface IHouseService
{
Task<IEnumerable<HouseModel>> Find();
}
}
依次调用
HouseService.cs
中的相同方法
using Task3.Controllers.Helper;
using Task3.Models;
namespace Task3.Controllers.Services
{
public class HouseService : IHouseService
{
private readonly HttpClient _client;
public const string BasePath = "/api/Houses";
public HouseService(HttpClient client)
{
_client = client ?? throw new ArgumentNullException(nameof(client));
}
public async Task<IEnumerable<HouseModel>> Find()
{
var response = await _client.GetAsync(BasePath);
return await response.ReadContentAsync<List<HouseModel>>();
}
}
}
调用
ReadContentAsync<List<HouseModel>>()
using Newtonsoft.Json;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace Task3.Controllers.Helper
{
public static class HttpClientExtensions
{
public static async Task<T> ReadContentAsync<T>(this HttpResponseMessage response)
{
if (response.IsSuccessStatusCode == false)
throw new ApplicationException($"Something went wrong calling the API: {response.ReasonPhrase}");
var dataAsString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Console.WriteLine(dataAsString);
var result = JsonSerializer.Deserialize<T>(dataAsString);
return result;
}
}
}
并且带有
Deserialize<T>
的行返回前面提到的错误。
我尝试的显然是调试,
Deserialize<T>
方法除了返回错误之外,还返回 null '因为它显然无法将 Json 结果转换为 Model 属性。这里是HouseModel
namespace Task3.Models;
public class HouseModel
{
public string Price { get; set; }
public string Region { get; set; }
public string PublicationDate { get; set; }
public string GeoLat { get; set; }
public string GeoLon { get; set; }
public string BuildingType { get; set; }
public string Area { get; set; }
public string Rooms { get; set; }
public string FloorNum { get; set; }
public string TotalFloor { get; set; }
public string ObjectType { get; set; }
public string Id { get; set; }
public string status { get; set; }
public string Photo { get; set; }
}
顺便说一句,在此之前
HouseModel
属性是 int、DateTime 等,错误是无法转换为 Int32。
我还使用了自定义转换器
StringConverter
public class StringConverter : System.Text.Json.Serialization.JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Number)
{
var stringValue = reader.GetInt32();
stringValue = stringValue;
return stringValue.ToString();
}
else if (reader.TokenType == JsonTokenType.String)
{
return reader.GetString();
}
throw new System.Text.Json.JsonException();
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
writer.WriteStringValue(value);
}
}
但在这种情况下,每个条目都是
null
。
有人可以分享一些见解吗?
我自己解决了这个问题。问题是我使用了两种不同的模型。 MVC 中的一个和 API 中的一个,它们具有不同的数据类型和变量名称,这是主要问题。
确保 Json 中的值与类的属性具有相同的数据类型非常重要。
public string CityName { get; set; }
json = "{\"CityName\":\"Bafoussam\"}"
如果是故意的,您还可以使用以下选项来允许从字符串中读取数字:
new JsonSerializerOptions()
{
NumberHandling = JsonNumberHandling.AllowReadingFromString
}