【问题标题】:How to generate class for JSON c#如何为 JSON c# 生成类
【发布时间】:2017-06-17 09:47:17
【问题描述】:

我现在将 Newtonsoft.Json 用于 JSON。也许有人知道我应该为这个 json 请求使用什么类?

{
"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
}

【问题讨论】:

标签: c# json json.net


【解决方案1】:

使用这个类

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 );

【讨论】:

  • 你的答案是正确的,和我的很像,但你的答案缺少(武器)名称。
  • @ThomasFlinkow 不,武器名称是响应目录的键值
  • 哦,我明白了,这是一个漂亮而优雅的答案。 +1
【解决方案2】:

如果所有这些 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)并通过使用步枪名称作为属性。

【讨论】:

    猜你喜欢
    • 2012-11-25
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多