我有这样的 JSON:
编辑:JSON 是错误的。我是手写的
var VehiclesData = {
"VehiclesData": {
"VehiclesList": [
{ "year": "2010", "make": "honda", "model": "civic" },
{ "year": "2011", "make": "toyota", "model": "corolla" },
{ "year": "2012", "make": "audi", "model": "a4" }]
}
}
我正在尝试将其发送到 .net Web 服务 API,如下所示:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string ProcessData(VehiclesData VehiclesData)
{
//...Do stuff here with VehiclesData
}
public class VehiclesData
{
public List<Vehicle> VehiclesList = new List<Vehicle>();
public class Vehicle
{
private string year = string.Empty;
private string make = string.Empty;
private string model = string.Empty;
public string Year { get { return this.year; } set { this.make = value; } }
public string Make { get { return this.make; } set { this.make = value; } }
public string Model { get { return this.model; } set { this.model = value; } }
}
}
我收到“对象与目标类型不匹配”。
对于平面 JSON 对象,我可以很好地获取数据,但是对于对象数组和 C# 列表,我有点迷失。
最佳答案
要按原样工作,我认为您的 JSON 对象需要如下所示: 即:
var VehiclesData = {
"VehiclesList":
[
{ "Year": "2010", "Make": "honda", "Model": "civic" },
{ "Year": "2011", "Make": "toyota", "Model": "corolla" },
{ "Year": "2012", "Make": "audi", "Model": "a4" }
]
};
或者,您应该能够使用一些属性来提供帮助。
[DataContract]
public class VehiclesData
{
[DataMember(Name = "year")]
public string Year { get; set; }
.
.
.
}
这将允许您在 JSON 对象中保留小写名称,但您仍然需要删除“VehiclesData”:{ 部分,因为我认为在序列化过程中 .NET 会假定这是一个属性。
关于c# - 将 json 对象数组发送到 .net Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26132822/