gpt4 book ai didi

c# - JsonConvert.DeserializeObject 在 .net 中不起作用

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

我没有让 JsonConvert.DeserializeObject 为我工作。我从服务中获得了正确的 JSON 值。在网上找不到任何东西,希望能在这里得到一点帮助:)

这是我的代码:

public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void tbPlate_OnServerChange(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(tbPlate.Text))
{
var _res = Responses(tbPlate.Text);

if (_res.Vehicles != null)
{
lblTestText.Text = _res.Vehicles.FirstOrDefault(r => r.regNr == tbPlate.Text)?.ToString();
}
else
{
lblTestText.Text = "No vehicle data";
}
}
}

private static VehicleResults Responses(string regNr)
{
var _jSon = "";
var _url = @"http://apis.is/car";
var _res = new VehicleResults();

var _request = (HttpWebRequest)WebRequest.Create($"{_url}?number={regNr}");

var _response = _request.GetResponse();

using (var _responseStream = _response.GetResponseStream())
{
var _reader = new StreamReader(_responseStream, Encoding.UTF8);
_jSon = _reader.ReadToEnd();
}

_res = JsonConvert.DeserializeObject<VehicleResults>(_jSon);
return _res;
}
}

public class VehicleResponse
{
[JsonProperty("registryNumber")]
public string regNr { get; set; }
public string number { get; set; }
public string factoryNumber { get; set; }
public string type { get; set; }
public string subType { get; set; }
public string color { get; set; }
public string registeredAt { get; set; }
public string status { get; set; }
public string nextCheck { get; set; }
public string pollution { get; set; }
public string weight { get; set; }
}

public class VehicleResults
{
public List<VehicleResponse> Vehicles { get; set; }
}

这是来自服务的响应 JSON:

{"results":[{"type":"MERCEDES BENZ - M (Svartur)","subType":"M","color":"Svartur","registryNumber":"GXS56","number":"GXS56","factoryNumber":"WDC1631131A539035","registeredAt":"23.09.2004","pollution":" g/km","weight":"2200 kg","status":"Í lagi","nextCheck":"01.06.2019"}]}

我对 REST 服务很陌生,所以我认为这个问题很小....我现在无法弄清楚。

最佳答案

您的 json 有一个根对象,其中包含您的车辆列表。
您需要使用 json 中返回的名称来命名保存列表的变量。 结果

public class VehicleResults
{
// This should be named results
public List<VehicleResponse> results {get;set;}
}

现在你可以反序列化

VehicleResults data = JsonConvert.DeserializeObject<VehicleResults>(json);
foreach(var vei in data.results)
Console.WriteLine(vei.type);

关于c# - JsonConvert.DeserializeObject 在 .net 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55894726/

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