我正在调用外部api服务,但是我遇到一个异常,它不会反序列化到我的模型中:
我的答复是
[
{
"$type": "Tfl.Api.Presentation.Entities.RoadCorridor,Tfl.Api.Presentation.Entities","id": "a2","displayName": "A2","statusSeverity": "Good","statusSeverityDescription": "No Exceptional Delays","bounds": "[[-0.0857,51.44091],[0.17118,51.49438]]","envelope": "[[-0.0857,[-0.0857,51.49438],51.44091]]","url": "/Road/a2"
}
]
我的代码是
public class TravelService : ITravelService
{
string baseURL = "https://foo.bar/blah.blah";
private readonly IMapToNew<Road,RoadDto> _mapper;
public TravelService()
{
}
public TravelService(IMapToNew<Road,RoadDto> mapper)
{
_mapper = mapper;
}
public async Task<RoadDto> GetTravelInformation()
{
var road = GetRoad();
Console.WriteLine(road.Result.DisplayName);
return new RoadDto
{
DisplayName = road.Result.DisplayName,StatusSeverityDescription = road.Result.DisplayName,StatusSeverity = road.Result.DisplayName
};
}
private async Task <Road> GetRoad()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseURL);
client.DefaultRequestHeaders.accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await client.Getasync(baseURL);
if (Res.IsSuccessStatusCode)
{
var roadResponse = Res.Content.ReadAsStringAsync().Result;
Road road = JsonConvert.DeserializeObject<Road>(roadResponse);
return new Road
{
DisplayName = road.DisplayName,StatusSeverity = road.StatusSeverity,StatusSeverityDescription = road.StatusSeverityDescription
};
}
return new Road { };
}
}
我的上课时间是:
public class Road
{
[JsonProperty(PropertyName = "$type")]
public string PropertyName { get; set; }
public string Id { get; set; }
public string DisplayName { get; set; }
public string StatusSeverity { get; set; }
public string StatusSeverityDescription { get; set; }
public string Bounds { get; set; }
public string Envelope { get; set; }
public string Url { get; set; }
}
运行代码时出现异常:“发生一个或多个错误。 (发生一个或多个错误。(无法将当前JSON数组(例如[1,2,3])反序列化为类型'Travel.Responses.Road',因为该类型需要JSON对象(例如{“ name”:“ value” })正确反序列化