[英]How to Convert Json list String to List in c#?
我需要将 json 列表字符串转换为 C# 列表
我的模型:
public class AddressModel
{
public string StateCode { get; set; }
public string CityCode { get; set; }
public string PinCode { get; set; }
public string Place { get; set; }
public string Street { get; set; }
public string DoorNo { get; set; }
public string State { get; set; }
public string City { get; set; }
public string AddresDetails{ get; set; }
}
杰森:
"[\n {\n \"input\": {\n \"statecode\": 1,\n \"citycode\": 12,\n \"pincode\": \"123\",\n \"addresdetails\": \"\"\n },\n \"output\": [\n \n ]\n },\n {\n \"input\": {\n \"statecode\": 2,\n \"citycode\": 45,\n \"pincode\": \"765\",\n \"addresdetails\": \"\"\n },\n \"output\": [\n \n ]\n }\n]";
我尝试使用 DeserializeObject 但它不起作用
变种模型 = JsonConvert.DeserializeObject(json);
我想把它转换成一个列表。 有人可以帮我吗?
这是一个适合我的示例
//Deserialize the JSON string with the model
List<Root> myList = JsonConvert.DeserializeObject<List<Root>>(strJSON);
foreach(Root rootObj in myList) {
//access properties of the deserialized object
Console.WriteLine(rootObj.Input.statecode);
}
更新:对于您的 JSON,您的模型应该是这样的;
public class Input
{
public int statecode { get; set; }
public int citycode { get; set; }
public string pincode { get; set; }
public string addresdetails { get; set; }
}
public class Root
{
public Input input { get; set; }
public List<object> output { get; set; }
}
您的 json 不仅仅是您的模型数组。 它们是数组中对象的输入。 您必须做更多的工作才能通过添加更多模型或操作 json 对象来将其反序列化。
var obj = JsonConvert.DeserializeObject<JArray>(json);
var addresses = obj.Select(x => x["input"].ToObject<AddressModel>()).ToList();
你必须修复你的课程
List<Data> data = JsonConvert.DeserializeObject<List<Data>>(json);
public partial class Data
{
[JsonProperty("input")]
public AddressModel Input { get; set; }
[JsonProperty("output")]
public List<Output> Output { get; set; }
}
public partial class AddressModel
{
[JsonProperty("statecode")]
public long Statecode { get; set; }
[JsonProperty("citycode")]
public long Citycode { get; set; }
[JsonProperty("pincode")]
public long Pincode { get; set; }
[JsonProperty("addresdetails")]
public string Addresdetails { get; set; }
}
public partial class Output
{
}
如果您只需要输入列表
List<AddressModel> inputs = data.Select(d =>d.Input ).ToList();
// or just using AddressModel
List<AddressModel> inputs = JArray.Parse(json).Select(d =>d["input"].ToObject<AddressModel>() ).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.