C# 使用C在数组中获取对象值时遇到问题#
我正在使用C#,无法获取以下JSON的JSON数据值: 我正在尝试获取以下对象的所有名称-值对: body.quotes.vehicle.key 及 body.quotes.prices.pricing-fixed.price JSON包含几个这样的“vehicle”和“prices”对象(针对不同的车辆类型重复),尽管为了保持代码简洁,我在下面只包含了一个 我可以看到“quotes”是一个包含多个vehicle和pricing对象的数组,但我被困在一个事实上,即每个包含的对象似乎都没有直接的名称-值对,因此我无法确定如何获得所需的值C# 使用C在数组中获取对象值时遇到问题#,c#,json.net,C#,Json.net,我正在使用C#,无法获取以下JSON的JSON数据值: 我正在尝试获取以下对象的所有名称-值对: body.quotes.vehicle.key 及 body.quotes.prices.pricing-fixed.price JSON包含几个这样的“vehicle”和“prices”对象(针对不同的车辆类型重复),尽管为了保持代码简洁,我在下面只包含了一个 我可以看到“quotes”是一个包含多个vehicle和pricing对象的数组,但我被困在一个事实上,即每个包含的对象似乎都没有直接的名
{
"version": 243,
"code": "0",
"body": {
"quotes": [
{
"vehicle": {
"id": null,
"title": "Any Vehicle",
"key": "R4",
"description": "4 Seater",
"group": "NOMAP"
},
"prices": {
"pricing-fixed": {
"id": "18277",
"title": "FIXED",
"type": "fixedfare",
"alt": false,
"cost": 25,
"price": 25,
"tip": 0,
"commission": 0.5,
"auto": "1",
"priority": 1,
"schedulable": "1",
"for_account": false,
"audit": {
"zonecharges": []
},
"attributeextras_cost": 0,
"attributeextras_price": 0,
"round_robin": 0,
"waitAndReturn": false,
"prebooking_extra_price": "0.00",
"waitAndReturnCostDiscount": 0,
"waitAndReturnPriceDiscount": 0
}
}
},
{
"vehicle": { ...//etc.
我已经尝试了以下C#代码,但是(string)iCabbiVehicleJson[“vehicle.key”]
为空。(我相信这条线就是问题所在?)
代码段:
string jsonResponseAsString = returnJson.ToString();
JObject iCabbiResponseJson = JObject.Parse(jsonResponseAsString);
List<iCabbiQuoteVehicleFare> vehicleFares = new List<iCabbiQuoteVehicleFare>();
foreach (JToken vehicleFare in iCabbiResponseJson.SelectToken("body.quotes"))
{
try
{
JObject iCabbiVehicleJson = JObject.Parse(vehicleFare.ToString());
string vehicleKey = (string)iCabbiVehicleJson["vehicle.key"];
decimal fare = (decimal)iCabbiVehicleJson["prices.pricing-fixed.price"];
vehicleFares.Add(new iCabbiQuoteVehicleFare
{
VehicleKey = vehicleKey,
Fare = fare
});
}
catch (Exception ex)
{
string errorMessage = ex.Message;
}
}
谢谢。我认为您可以将它们视为
动态
并使用for
循环对它们进行迭代。我只是用你的示例数据做了一些类似的事情,它似乎起了作用
//数据变量保存json字符串的位置
var json=JsonConvert.DeserializeObject(数据);
var count=json.body.quotes.count;
对于(变量i=0;i
问题在于JToken的方括号索引器语法不支持虚线属性路径。您需要使用SelectToken()
方法进行此操作
更改这些行:
string vehicleKey = (string)iCabbiVehicleJson["vehicle.key"];
decimal fare = (decimal)iCabbiVehicleJson["prices.pricing-fixed.price"];
为此:
string vehicleKey = (string)iCabbiVehicleJson.SelectToken("vehicle.key");
decimal fare = (decimal)iCabbiVehicleJson.SelectToken("prices.pricing-fixed.price");
Fiddle:如果您使用的是最新的Visual Studio,您可以将JSON粘贴为.net类。谢谢。是的,我以前做过,但是这个JSON是从一个API调用中获得的,并且生成这个JSON的供应商经常更改我发现在这个场景中迭代JSON更稳定的结构。我怀疑如果他们不断更改JSON,这个结构是否会变得稳定schema@DetectivePikachu. 对这在过去引起了一些问题。答对了!完美的也谢谢你的解释。。。今天我学到了一些新东西。
string vehicleKey = (string)iCabbiVehicleJson.SelectToken("vehicle.key");
decimal fare = (decimal)iCabbiVehicleJson.SelectToken("prices.pricing-fixed.price");