使用C#反序列化JSON文件

时间:2014-05-28 19:58:15

标签: c# json.net

我正在创建一个Steam APP(对于Steam平台),我需要反序列化一个JSON文件。

{
"response": {
    "success": 1,
    "current_time": 1401302092,
    "raw_usd_value": 0.245,
    "usd_currency": "metal",
    "usd_currency_index": 5002,
    "items": {
        "A Brush with Death": {
            "defindex": [
                30186
            ],
            "prices": {
                "6": {
                    "Tradable": {
                        "Craftable": [
                            {
                                "currency": "metal",
                                "value": 4,
                                "last_update": 1398990171,
                                "difference": 0.17
                            }
                        ]
                    }
                }
            }
        },
...

我只需要获得Defindex和价值。已经反序列化了一些简单的JSON文件,但我认为这个文件更复杂。

对于那些想知道的人,我正在使用BackpackTF的API ...

4 个答案:

答案 0 :(得分:2)

使用NewtonSoft.Json然后您可以按如下方式使用它来获取数据。

    dynamic json = JsonConvert.DeserializeObject(<yourstring>);
    string currency = json.response.usd_currency;  // "metal"

答案 1 :(得分:1)

通常,您要做的是确保您拥有有效的JSON(使用JSON LINT),然后使用Json2CSharp获取C#类定义,然后您将执行以下操作:

MyClass myobject=JsonConvert.DeserializeObject<MyClass>(json);

(我们假设MyClass基于你从Json2CSharp获得的东西)

然后,您可以通过传统的C#点表示法访问所需的值。

答案 2 :(得分:0)

使用nuget包调用者Newtonsoft.Json.5.0.8。它位于nuget存储库中。

答案 3 :(得分:0)

这行代码将json作为字符串,并将其转换为根对象。

RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonString);

你提供的Json有点瑕疵,但是我猜你正在寻找的c#对象的结构将接近这个:

public class Craftable
{
    public string currency { get; set; }
    public int value { get; set; }
    public int last_update { get; set; }
    public double difference { get; set; }
}

public class Tradable
{
    public List<Craftable> Craftable { get; set; }
}

public class Prices
{
    public Tradable Tradable{ get; set; }
}

public class Items
{
    public List<int> defindex { get; set; }
    public Prices prices { get; set; }
}

public class Response
{
    public int success { get; set; }
    public int current_time { get; set; }
    public double raw_usd_value { get; set; }
    public string usd_currency { get; set; }
    public int usd_currency_index { get; set; }
    public Items items { get; set; }
}

public class RootObject
{
    public Response response { get; set; }
}
相关问题