我没有让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服务还很陌生,所以我认为问题很小。...我现在无法解决。
答案 0 :(得分:3)
您的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);
答案 1 :(得分:0)
您需要对VehicleResponse中的每个属性进行[JsonProperty]
请在使用结束时添加_reader.Close()