从 C# 中的 json 获取值

Get value from a json in c#

我正在尝试从更大的 json 中获取价值,但我几乎完全迷失了实施 it.Kindly 指南 me.I 已经提供了我的 json 字符串和 c#我试过的代码。

c#代码:

string cityname = "";
            string strCity = File.ReadAllText("E:/HotelResult.txt");
            dynamic city = JsonConvert.DeserializeObject(strCity);
            foreach (var hotel in city)
            {
               
                    cityname = hotel.type;
                
            }

Hotel.Result(Json):

{
  "data": [
    {
      "type": "hotel-offers",
      "hotel": {
        "type": "hotel",
        "hotelId": "ALNYC647",
        "chainCode": "AL",
        "dupeId": "501447323",
        "name": "Aloft Manhattan Downtown - Financial District",
        "rating": "4",
        "cityCode": "NYC",
        "latitude": 40.71041,
        "longitude": -74.00666,
        "hotelDistance": {
          "distance": 0.4,
          "distanceUnit": "KM"
        },
        "address": {
          "lines": [
            "49 53 ANN STREET"
          ],
          "postalCode": "10038",
          "cityName": "NEW YORK",
          "countryCode": "US",
          "stateCode": "NY"
        },
        "contact": {
          "phone": "+1 212 513-0003",
          "fax": "+1 212 513-0004",
          "email": "info@aloftmanhattandowntown.com"
        },
        "description": {
          "lang": "en",
          "text": "Celebrate your style at Aloft Manhattan Downtown - Financial District, a hip new hotel where you'll be close to corporate headquarters, Wall Street and the World Trade Center. We offer easy-breezy access to Big Apple hotspots via nearby subway lines. Meet & mingle with friends at our w xyz(SM) bar, grab a sweet, savory or healthy snack from re:fuel by Aloft(SM), our 24/7 pantry or play in our re:mix(SM) lounge. Plus, you can always stay connected with free hotel-wide wired and wireless High Speed Internet Access! Breeze into one of our Aloft rooms, featuring our ultra-comfortable signature bed, walk-in shower, custom amenities by Bliss® Spa and more."
        },
        "amenities": [
          "SPA",
          "SERV_DOGS_ALWD",
          "ACC_TOILETS",
          "HANDRAIL_BTHRM",
          "24_HOUR_FRONT_DESK",
          "CAR_RENTAL",
          "EXPRESS_CHECK_IN",
          "LOUNGE",
          "ICE_MACHINES",
          "FLORIST",
          "TRAVEL_AGENCY",
          "CONCIERGE",
          "SAFE_DEP_BOX",
          "LAUNDRY_SVC",
          "ATM/CASH_MACHINE",
          "EXPRESS_CHECK_OUT",
          "WEDDING_SERVICES",
          "GYM",
          "RESTAURANT",
          "HI_INTERNET",
          "FREE_INTERNET",
          "WIRELESS_CONNECTIVITY",
          "ELEVATOR",
          "PETS_ALLOWED",
          "PHOTOCOPIER",
          "PRINTER",
          "BUSINESS_CENTER",
          "MEETING_FACILITIES",
          "INTERNET-HI_SPEED_IN_RM",
          "WI-FI_IN_ROOM",
          "NONSMOKING_RMS",
          "FREE_LOCAL_CALLS",
          "TEA/COFFEE_MK_FACILITIES",
          "ALARM_CLOCK",
          "AIR_CONDITIONING",
          "SAFE",
          "IRON/IRON_BOARD",
          "CRIBS_AVAILABLE",
          "TELEVISION",
          "HAIR_DRYER",
          "VOICEMAIL_IN_ROOM",
          "PHONE-DIR_DIAL",
          "CORDLESS_PHONE",
          "REFRIGERATOR",
          "OUTLET_ADAPTERS",
          "CABLE_TELEVISION",
          "FITNESS_CENTER"
        ]
      },
      "available": true,
      "offers": [
        {
          "id": "LBRB9R0B0X",
          "checkInDate": "2020-09-13",
          "checkOutDate": "2020-09-14",
          "rateCode": "S9R",
          "rateFamilyEstimated": {
            "code": "SRS",
            "type": "C"
          },
          "room": {
            "type": "XMI",
            "typeEstimated": {
              "beds": 1,
              "bedType": "QUEEN"
            },
            "description": {
              "lang": "EN",
              "text": "Marriott Senior Discount, includes 62 years and older valid ID \nSleeps 2, Fast & free WiFi throughout the hotel\n, 1 Queen, 200sqft/18sqm-220sqft/20sqm, Wireles"
            }
          },
          "guests": {
            "adults": 1
          },
          "price": {
            "currency": "USD",
            "base": "127.00",
            "total": "149.25",
            "variations": {
              "average": {
                "base": "127.00"
              },
              "changes": [
                {
                  "startDate": "2020-09-13",
                  "endDate": "2020-09-14",
                  "base": "127.00"
                }
              ]
            }
          },
          "policies": {
            "paymentType": "guarantee",
            "cancellation": {
              "deadline": "2020-09-13T09:29:00+05:30"
            }
          }
        }
      ],
      "self": "https://test.api.amadeus.com/v2/shopping/hotel-offers/by-hotel?hotelId=ALNYC647"
    },
    {
      "type": "hotel-offers",
      "hotel": {
        "type": "hotel",
        "hotelId": "HXNYC432",
        "chainCode": "HX",
        "dupeId": "700051862",
        "name": "HAMPTON INN MANHATTAN-DOWNTOWN-FINANCIAL",
        "rating": "2",
        "cityCode": "NYC",
        "latitude": 40.70312,
        "longitude": -74.01228,
        "hotelDistance": {
          "distance": 1.3,
          "distanceUnit": "KM"
        },
        "address": {
          "lines": [
            "32 PEARL ST"
          ],
          "postalCode": "10004",
          "cityName": "NEW YORK",
          "countryCode": "US",
          "stateCode": "NY"
        },
        "contact": {
          "phone": "1-212-480-3500",
          "fax": "1-212-480-3700"
        },
        "amenities": [
          "BUSINESS_CENTER",
          "ADAPTED_PHONES",
          "WIDE_ENTRANCE",
          "WIDE_CORRIDORS",
          "FIRST_AID_STAF",
          "INT_ROOM_ENTRY",
          "EMERG_LIGHTING",
          "FIRE_DETECTORS",
          "EXTINGUISHERS",
          "FIRE_SAFETY",
          "RESTRIC_RM_ACC",
          "SMOKE_DETECTOR",
          "SPRINKLERS",
          "LAUNDRY_SVC",
          "PARKING",
          "PETS_ALLOWED",
          "SAFE_DEP_BOX",
          "AIR_CONDITIONING",
          "HAIR_DRYER",
          "MOVIE_CHANNELS",
          "NONSMOKING_RMS",
          "PC_HOOKUP_INRM",
          "TELEVISION",
          "FITNESS_CENTER"
        ],
        "media": [
          {
            "uri": "http://uat.multimediarepository.testing.amadeus.com/cmr/retrieve/hotel/9E95CFEC3B6F4C459EDC0F267159B799",
            "category": "EXTERIOR"
          }
        ]
      },
      "available": true,
      "offers": [
        {
          "id": "Y0IT2BLO9V",
          "checkInDate": "2020-09-13",
          "checkOutDate": "2020-09-14",
          "rateCode": "RAC",
          "rateFamilyEstimated": {
            "code": "AAA",
            "type": "C"
          },
          "commission": {
            "percentage": "10.00"
          },
          "boardType": "BREAKFAST",
          "room": {
            "type": "C1Q",
            "typeEstimated": {
              "category": "ACCESSIBLE_ROOM",
              "beds": 1,
              "bedType": "QUEEN"
            },
            "description": {
              "lang": "EN",
              "text": "AAA RATE\n1 QUEEN ACCESSIBLE ROLL IN SHOWER NONSMOKING\nHDTV/WORK AREA"
            }
          },
          "guests": {
            "adults": 1
          },
          "price": {
            "currency": "USD",
            "base": "594.15",
            "total": "685.29",
            "variations": {
              "average": {
                "base": "594.15"
              },
              "changes": [
                {
                  "startDate": "2020-09-13",
                  "endDate": "2020-09-14",
                  "base": "594.15"
                }
              ]
            }
          },
          "policies": {
            "paymentType": "guarantee",
            "cancellation": {
              "deadline": "2020-09-10T09:30:00+05:30"
            }
          }
        }
      ],
      "self": "https://test.api.amadeus.com/v2/shopping/hotel-offers/by-hotel?hotelId=HXNYC432"
    },
    {
      "type": "hotel-offers",
      "hotel": {
        "type": "hotel",
        "hotelId": "BWNYC133",
        "chainCode": "BW",
        "dupeId": "700101379",
        "name": "Best Western Bowery Hanbee Hotel",
        "rating": "2",
        "cityCode": "NYC",
        "latitude": 40.7184,
        "longitude": -73.99518,
        "hotelDistance": {
          "distance": 1.0,
          "distanceUnit": "KM"
        },
        "address": {
          "lines": [
            "231 GRAND STREET"
          ],
          "postalCode": "10013",
          "cityName": "NEW YORK CITY",
          "countryCode": "US",
          "stateCode": "NY"
        },
        "contact": {
          "phone": "+1 212 9251177",
          "fax": "+1 212 9255533",
          "email": "33133@hotel.bestwestern.com"
        },
        "description": {
          "lang": "en",
          "text": "Stay at this 100% non-smoking New York City, New York hotel located next to the subway and key local attractions such as Canal Street, Chinatown and Little Italy. Welcome to the Best Western Bowery Hanbee Hotel, where guests will find exceptional customer service and accommodations at an affordable rate. This New York City hotel features well-appointed guest rooms and suites, each offering cable satellite television with free HBO® and free wireless high-speed Internet access. Guests staying at this 100% non-smoking hotel will enjoy a complimentary hot breakfast buffet each morning before heading out to sightsee. Additional amenities include an exercise facility and a full-service business center. The Best Western Bowery Hanbee Hotel is ideally located less than one mile from many New York attractions including Chinatown, Little Italy, the Wall Street financial district and the World Trade Center Memorial. Hotel guests will enjoy an afternoon of shopping on 5th Avenue or visiting key sights such as Ellis Island, the Statue of Liberty, the Empire State Building and Times Square. Corporate travelers will appreciate being a half mile from the New York Stock Exchange, the Federal Reserve Bank, JP Morgan and American Express®. This New York hotel is also ideal for viewing several annual events including the Macy's Thanksgiving Day Parade®, the Chinese New Year and the Tribeca Film Festival. The friendly, helpful staff at the Best Western Bowery Hanbee Hotel is ready to ensure a fun-filled memorable stay in New York, New York. Make a reservation today and save! Enjoy your stay!"
        },
        "amenities": [
          "24_HOUR_FRONT_DESK",
          "GYM",
          "HI_INTERNET",
          "ELEVATOR",
          "ICE_MACHINES",
          "SPRINKLERS",
          "FIRE_DETECTORS",
          "FEMA_FIRE_SAFETY_COMPLIANT",
          "SMOKE_DETECTOR",
          "EMERG_LIGHTING",
          "HANDICAP_FAC",
          "BUSINESS_CENTER",
          "FREE_LOCAL_CALLS",
          "PHONE-DIR_DIAL",
          "INTERNET-HI_SPEED_IN_RM",
          "HAIR_DRYER",
          "AIR_CONDITIONING",
          "CABLE_TELEVISION",
          "VOICEMAIL_IN_ROOM",
          "SAFE",
          "WAKEUP_SERVICE",
          "ALARM_CLOCK",
          "TEA/COFFEE_MK_FACILITIES",
          "CRIBS_AVAILABLE"
        ],
        "media": [
          {
            "uri": "http://uat.multimediarepository.testing.amadeus.com/cmr/retrieve/hotel/A15115741A8747538ECDBB2AA76B7DE9",
            "category": "EXTERIOR"
          }
        ]
      },
      "available": true,
      "offers": [
        {
          "id": "MLX8YR77R7",
          "checkInDate": "2020-09-13",
          "checkOutDate": "2020-09-14",
          "rateCode": "SRS",
          "rateFamilyEstimated": {
            "code": "SRS",
            "type": "C"
          },
          "commission": {
            "percentage": "10"
          },
          "boardType": "BREAKFAST",
          "room": {
            "type": "A1Q",
            "typeEstimated": {
              "category": "ACCESSIBLE_ROOM",
              "beds": 1,
              "bedType": "QUEEN"
            },
            "description": {
              "lang": "EN",
              "text": "SENIOR RATE*CITIZENS 55YRS PLUS OR AARP ID\n1 QUEEN BED,MOBILITY ACC,COMMASSIST,ROLL SHWR,\nNSMK,CONTINENTAL BREAKFAST"
            }
          },
          "guests": {
            "adults": 1
          },
          "price": {
            "currency": "USD",
            "base": "242.10",
            "total": "281.31",
            "variations": {
              "average": {
                "base": "242.10"
              },
              "changes": [
                {
                  "startDate": "2020-09-13",
                  "endDate": "2020-09-14",
                  "base": "242.10"
                }
              ]
            }
          },
          "policies": {
            "paymentType": "guarantee",
            "cancellation": {
              "deadline": "2020-09-11T09:30:00+05:30"
            }
          }
        }
      ],
      "self": "https://test.api.amadeus.com/v2/shopping/hotel-offers/by-hotel?hotelId=BWNYC133"
    }
  ],
  "meta": {
    "links": {
      "next": "https://test.api.amadeus.com/v2/shopping/hotel-offers?cityCode=NYC&page[offset]=BF2MJFOB9ASN_100"
    }
  }
}

现在我需要访问 json 的名称、描述和联系方式。请帮助我感到震惊 this.The 指针没有进入酒店 child。

我为 json 使用 JObject,它的工作原理是这样的:

string json = File.ReadAllText("E:/HotelResult.txt");
JObject o = JObject.Parse(json);
string name = (string)o["data"]["name"];
string contactPhone = (string)o["data"]["contact"]["phone"];

希望能帮到你

我只提取了你的部分代码做了一个例子

using System;
using Newtonsoft.Json;
                    
public class Program
{

    public static void Main()
    {
        string cityname = "";
        string json = "{\"data\": [{\"type\": \"hotel-offers\",\"hotel\": {\"type\": \"hotel\",\"hotelId\": \"ALNYC647\",\"chainCode\": \"AL\",\"dupeId\": \"501447323\",\"name\": \"Aloft Manhattan Downtown - Financial District\",\"rating\": \"4\",\"cityCode\": \"NYC\",\"latitude\": 40.71041,\"longitude\": -74.00666,\"hotelDistance\": {\"distance\": 0.4,\"distanceUnit\": \"KM\"}}}]}";
        dynamic parsedJson = JsonConvert.DeserializeObject(json);
        cityname = parsedJson.data[0].hotel.name;
        Console.WriteLine(cityname);
    }
}

同时复制动态和城市名称可以解决您的问题。您应该注意您的模型可能存在的其他一些问题。

1 - 如果您的 json 数据中有多行,您将只会获得最后一个城市名称。你会失去所有其他的

2 - 正如@Marco 在您的评论中指出的那样,实际映射 json

会更好