2014-10-01 47 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 
} 

這對我有用。希望它可以幫助其他人