c# - 使用 C# 的 Newtonsoft.Json 从 JSON 获取数据

标签 c# json.net

这是我的 json 数据文件内容:

{
    "mercedes": {
        "model" : "GLS 350 d 4MATIC",
        "code" : "MB-GLS",
        "year": 2015
    },
    "bmw": {
        "model" : "BMW 420d Cabrio",
        "code" : "BM-420D",
        "year": 2017
    },
    "audi": {
        "model" : "A5 Sportback 2.0 TDI quattro",
        "code" : "AU-A5",
        "year": 2018
    },
    "tesla": {
        "model" : "Model S",
        "code" : "TS-MOS",
        "year": 2016
    },
  "test_drive": 0,
  "path": "D:\\Mizz\\cars\\"
}

首先,我的json结构对吗?然后我想将“模型”属性作为列表获取。但我对此一无所知。

最佳答案

如果你能改变你的数据结构,那将是理想的。你现在拥有的那个不会很好地扩展。

{
    "vehicles": [
        {
            "mfgr": "mercedes",
            "model" : "GLS 350 d 4MATIC",
            "code" : "MB-GLS",
            "year": 2015
        },
        {
            "mfgr": "bmw",
            "model" : "BMW 420d Cabrio",
            "code" : "BM-420D",
            "year": 2017
        },
        {
            "mfgr": "audi",
            "model" : "A5 Sportback 2.0 TDI quattro",
            "code" : "AU-A5",
            "year": 2018
        },
        {
            "mfgr": "tesla",
            "model" : "Model S",
            "code" : "TS-MOS",
            "year": 2016
        }
    ],
  "testDrive": 0,
  "path": "D:\\Mizz\\cars\\"
}

然后您需要在 C# 中为“汽车”类型建模。

public class Car
{
   public string Mfgr { get; set; }
   public string Model { get; set; }
   public string Code { get; set; }
   public int Year { get; set; }
}

还有外部对象类型。

public class MyOuterType
{
    public List<Car> Vehicles { get; set; }
    public int TestDrive { get; set; }
    public string Path { get; set; }
}

然后你可以使用JsonConvert.Deserialize<MyOuterType>(theJson);得到你的对象。

关于c# - 使用 C# 的 Newtonsoft.Json 从 JSON 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50308945/

相关文章:

c# - Json.net 反序列化为 Json 中可能包含数组或嵌套数组的对象

c# - Datagridview 行重复

c# - C#中的类可以指向它自己吗

c# - MVVM 事件处理程序属于哪里

c# - 将 JSON 反序列化为泛型,其中集合属性名称根据类型而变化

asp.net-mvc - ASP.NET MVC Controller 无法使用流式内容正确返回 HttpResponseMessage

c# - Elasticsearch-按分数过滤前N个文档,然后按字段排序

c# - 使用 AutoMapper 覆盖已解析的属性类型

c# - Json.NET XML 转换和 TypeNameHandling.Arrays

c# - 如何将 C# 对象序列化为 json,使其看起来像 "["开头为", "$key", "user/john/"]"?