gpt4 book ai didi

c# - 使用 C# 获取数组中的对象值时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:29 25 4
gpt4 key购买 nike

我正在使用 C#,无法获取以下 JSON 的 JSON 数据值:

我正在尝试获取所有名称值对:

body.quotes.vehicle.key

body.quotes.prices.pricing-fixed.price

JSON 包含几个这样的“车辆”和“价格”对象(针对不同的车辆类型重复),尽管我在下面只包含一个以保持代码简洁。

我可以看到“quotes”是一个包含多个车辆和定价对象的数组,但我一直坚持这样一个事实,即每个包含的对象似乎都没有直接的名称值对,所以我无法工作了解如何获得我需要的值。

{
"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;
}
}

变量 vehicleFares 实际上返回以下内容。双花括号很可能是问题所在......

{{
"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,

谢谢。

最佳答案

问题是 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 :https://dotnetfiddle.net/nkSu5y

关于c# - 使用 C# 获取数组中的对象值时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57930631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com