如何将Json列表字符串转换为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; }

}
Json:

"[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,但它不起作用

var model = JsonConvert.DeserializeObject(json);

我想把它转换成一个列表。有人能帮我一下吗?

json不仅仅是一个模型数组。它们是数组中对象的输入。你必须做更多的事情来让它以反序列化的形式出现,或者通过添加更多的模型,或者操作json对象。

var obj = JsonConvert.DeserializeObject<JArray>(json);
var addresses = obj.Select(x => x["input"].ToObject<AddressModel>()).ToList();

下面是一个适合我的示例

//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; }
}

你必须修复你的类

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();

最新更新