2017-06-28 36 views
1

我有我在RestClient中發佈的以下json數據。如何從Rest客戶端發佈單個對象時獲取json數據?

{ 
    "Cars": [ 
     { 
     "color":"Blue", 
     "miles":100, 
     "vin":"1234" 
     }, 
     { 
     "color":"Red", 
     "miles":400, 
     "vin":"1235" 
     } 
    ], 
    "truck": { 
    "color":"Red", 
    "miles":400, 
    "vin":"1235" 
    } 
} 

,我試圖在服務器端,而得到這個JSON在一個單一的對象也從REST客戶端發佈

public JsonResult Post([FromBody]Object Cars) 
{ 
    return Cars; 
} 

我怎樣才能得到這個JSON在一個單一的對象?

+0

您只對JSON車或整個物體感興趣嗎? –

+0

我需要JSON在一個對象從我可以得到汽車參數值如顏色,英里,Vin等在服務器端。 –

+0

是的,我需要一個完整的對象。 –

回答

-1

這已經被問了很多次才:Posting array of objects with MVC Web API

您可以使用一個類來表示目標是更好地

public class Vehicle 
{ 
    public string color; 
    public string type; 
    public int miles; 
    public int vin; 
} 

然後你可以使用:

public JsonResult Post([FromBody]Vehicle[] vehicles) 
{ 
    return vehicles; 
} 

隨着數據如:

[ 
    { 
    "color":"Blue", 
    "type": "car" 
    "miles":100, 
    "vin":"1234" 
    }, 
    { 
    "color":"Red", 
    "type": "car" 
    "miles":400, 
    "vin":"1235" 
    }, 
    { 
    "color":"Red", 
    "type": "truck" 
    "miles":400, 
    "vin":"1235" 
    } 
] 
+1

呃,爲什麼downvote?請解釋 –

0

如果你需要整個JSON到一個對象中,那麼我在這裏使用json2csharp.com將你的JSON轉換成類。

public class Car 
{ 
    public string color { get; set; } 
    public int miles { get; set; } 
    public string vin { get; set; } 
} 

public class Truck 
{ 
    public string color { get; set; } 
    public int miles { get; set; } 
    public string vin { get; set; } 
} 

public class RootObject 
{ 
    public List<Car> Cars { get; set; } 
    public Truck truck { get; set; } 
} 

您的API更改爲:

public JsonResult Post([FromBody]RootObject root) 
{ 
    return root.Cars; // List<Car> 
} 

現在您可以訪問Carstruck

相關問題