【问题标题】:Sending json object array to .net web service将 json 对象数组发送到 .net Web 服务
【发布时间】:2014-11-25 18:56:40
【问题描述】:

我有这样的 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# 列表,我有点迷茫。

【问题讨论】:

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


【解决方案1】:

要按原样工作,我认为您的 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 将假定这是一个属性。

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-03
      • 2014-02-10
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 2011-02-08
      • 1970-01-01
      相关资源
      最近更新 更多