2014-10-01 46 views
2

我有JSON这样的:
编辑:JSON是错误的。发送json对象数组到.net web服务

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

我收到“对象不匹配目标类型”:我曾用手

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这样的类型吧。

有了扁平的JSON对象,我得到的数据很好,但对象和一个C#列表的数组,我有点失落。

+0

你的json无效http://json2csharp.com/ – saj 2014-10-01 01:43:05

回答

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对象小写的名字,但你仍然需要删除“VehiclesData”:{部分原因是我想序列化.NET期间会认为是一个属性。

1

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

我确实改变了JSON是一个级别以下(同什么peinearydevelopment说的),使其不仅具有Vehicle对象的数组,然后将WebMethod我接受了车辆对象类型的列表:

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

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