将json对象数组发送到.net Web服务

时间:2014-10-01 01:38:25

标签: c# asp.net json web-services asmx

我有这样的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 Service 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; } }
     }
}

我得到&#34;对象与目标类型不匹配&#34;。

使用平面JSON对象,我可以很好地获取数据,但是对于一组对象和一个c#List,我有点迷失。

2 个答案:

答案 0 :(得分:2)

要按原样工作,我认为您的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对象中维护小写名称,但是您仍然需要删除&#34; VehiclesData&#34;:{部分因为我认为在序列化期间.NET将假定这是一个属性。

答案 1 :(得分:1)

我会将peinearydevelopment的答案标记为这个问题的正确答案。我最后采取了一些不同的方法,但总的来说与他所说的非常相似。

我确实将JSON更改为一级(与peinearydevelopment所说的相同),以便它只有一个Vehicle对象的数组,然后在WebMethod中我接受了一个Vehicle对象类型的列表:

[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string ProcessData(List<Vehicle> Vehicles)
{
    //.. Do stuff here
}

这对我有用。希望它可以帮助其他人