使用c#反序列化JSON文件

本文关键字:文件 JSON 反序列化 使用 | 更新日期: 2023-09-27 18:05:33

我正在创建一个Steam应用程序(用于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…

使用c#反序列化JSON文件

使用NewtonSoft。然后,您可以像下面这样使用它来获取数据。

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

一般来说,你要做的是确保你有有效的JSON(使用JSON LINT),然后用Json2CSharp得到一个c#类定义,然后你会做这样的事情:

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

(我们假设MyClass是基于你从Json2CSharp得到的)

然后你通过传统的c#点表示法访问你想要的值

使用nuget包调用器Newtonsoft.Json.5.0.8。

这行代码将把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; }
}