2017-06-17 80 views
-5

我現在使用的是用於JSON的Newtonsoft.Json。也許有人知道我的這個json請求使用什麼類?如何爲JSON生成類c#

{ 
"status": 1, 
"response": { 
    "AK-47 | Aquamarine Revenge (Battle-Scarred)": { 
     "price": 929, 
     "quantity": 46 
    }, 
    "AK-47 | Aquamarine Revenge (Factory New)": { 
     "price": 2716, 
     "quantity": 100 
    }, 
    "AK-47 | Aquamarine Revenge (Field-Tested)": { 
     "price": 1349, 
     "quantity": 345 
    }, 
    "AK-47 | Aquamarine Revenge (Minimal Wear)": { 
     "price": 1919, 
     "quantity": 143 
    }, 
    "AK-47 | Aquamarine Revenge (Well-Worn)": { 
     "price": 1135, 
     "quantity": 204 
    }, 
    "AK-47 | Black Laminate (Factory New)": { 
     "price": 6999, 
     "quantity": 14 
    }, 
    "AK-47 | Black Laminate (Field-Tested)": { 
     "price": 671, 
     "quantity": 83 
} 
}, 
    "time": 1497616580 
} 
+1

http://json2csharp.com/ –

回答

1

提供所有這些AK ...類來自同一派生,你應該能夠使用(儘管不建議這樣做,見下面我的編輯):

public class Weapon 
{ 
    public int price { get; set; } 
    public int quantity { get; set; } 
} 

public class AK47AquamarineRevengeFieldTested : Weapon 
{ 
} 

public class AK47AquamarineRevengeMinimalWear : Weapon 
{ 
} 

// etc., do this for each AK... class 

public class Response 
{ 
    public Weapon AK47AquamarineRevengeFieldTested { get; set; } 
    public Weapon AK47AquamarineRevengeMinimalWar { get; set; } 

    // Add all those weapons here, or use (you need a different JSON result though) 
    public IEnumerable<Weapon> Weapons { get ; set; } 
} 

public class Example 
{ 
    public int status { get; set; } 
    public Response response { get; set; } 
    public int time { get; set; } 
} 

編輯: 一般來說,如果你可以重新設計你的代碼,你很可能會做這種方式:

public class Weapon 
{ 
    public string name { get; set; } 
    public int price { get; set; } 
    public int quantity { get; set; } 
} 

然後你就可以使用它像這樣:

IEnumerable<Weapon> Weapons = new List<Weapon> 
{ 
    new Weapon { name = "AK47AquamarineRevengeFieldTestet", price = .., quantity = ..}, 
    new Weapon { name = "AK47AquamarineRevengeMinimalWar", price = .., quantity = ..}, ... 
} 

因此,您不會爲每支步槍創建不同的類,而只需使用一支步槍類(本例中爲Weapon),並將步槍名稱作爲屬性使用。

2

使用該班

class StockResponse 
{ 
    public int status { get; set; } 
    public int time { get; set; } 
    public Dictionary<string,StockData> response { get; set; } 
} 

class StockData 
{ 
    public int price { get; set; } 
    public int quantity { get; set; } 
} 

,並與反序列化

var response = JsonConvert.DeserializeObject<StockResponse>(jsonResponse); 
+0

你的答案是正確的,很像我的,但你缺少的(武器)名稱。 –

+0

@ThomasFlinkow不,武器名稱是響應目錄的關鍵值 –

+0

哦,我明白了,那是一個不錯而優雅的答案。 +1 –