我无法使其发挥作用。这是JSON:
https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/59/modelos
这是我的代码:
using (var client = new WebClient())
{
var url = string.Format("https://fipe-parallelum.rhcloud.com/api/v1/{0}/marcas/{1}/modelos", tipo_cb.SelectedValue, marca_cb.SelectedValue);
//Download do resultado
var json = client.DownloadString(url);
List<Modelos> plist = JsonConvert.DeserializeObject<List<Modelos>>(json);
foreach (Modelos data in plist)
{
modelo_cb.Items.Add(new ListItem(data.nome.ToString(), data.codigo.ToString()));
}
}
类
public class Modelos
{
public string nome;
public string codigo;
}
谢谢!
答案 0 :(得分:0)
问题是您的数据模型与您的JSON不匹配。您的根JSON容器是一个对象(名称/值对的集合,由大括号括起),而不是数组:{"modelos":[...]}
。这样的对象需要映射到非集合c#对象,如Json.NET documentation中所述。事实上,如果您只是将JSON链接发布到http://json2csharp.com/,它将为您设计正确的数据模型:
public class Modelo
{
public string nome { get; set; }
public int codigo { get; set; }
}
public class Ano
{
public string nome { get; set; }
public string codigo { get; set; }
}
public class RootObject
{
public List<Modelo> modelos { get; set; }
public List<Ano> anos { get; set; }
}
然后按如下方式反序列化:
List<Modelo> plist;
using (var client = new WebClient())
{
var url = @"https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/59/modelos";
//Download do resultado
var json = client.DownloadString(url);
var root = JsonConvert.DeserializeObject<RootObject>(json);
plist = root.modelos;
}
示例fiddle。