这是我的 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/