微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从C#中的JSON获取值

如何解决从C#中的JSON获取值

我正试图从更大的json中获取价值,但是我在实现它方面几乎迷失了。请指导我。我给出了我尝试过的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","hotelId": "HXNYC432","chainCode": "HX","dupeId": "700051862","name": "HAMPTON INN MANHATTAN-DOWNTOWN-FINANCIAL","rating": "2","latitude": 40.70312,"longitude": -74.01228,"hoteldistance": {
          "distance": 1.3,"address": {
          "lines": [
            "32 PEARL ST"
          ],"postalCode": "10004","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","PARKING","MOVIE_CHANNELS","PC_HOOKUP_INRM","fitness_CENTER"
        ],"media": [
          {
            "uri": "http://uat.multimediarepository.testing.amadeus.com/cmr/retrieve/hotel/9E95CFEC3B6F4C459EDC0F267159B799","category": "EXTERIOR"
          }
        ]
      },"offers": [
        {
          "id": "Y0IT2BLO9V","rateCode": "RAC","rateFamilyEstimated": {
            "code": "AAA","commission": {
            "percentage": "10.00"
          },"boardType": "BREAKFAST","room": {
            "type": "C1Q","typeEstimated": {
              "category": "ACCESSIBLE_ROOM","beds": 1,"text": "AAA RATE\n1 QUEEN ACCESSIBLE ROLL IN SHOWER NONSMOKING\nHDTV/WORK AREA"
            }
          },"base": "594.15","total": "685.29","variations": {
              "average": {
                "base": "594.15"
              },"base": "594.15"
                }
              ]
            }
          },"cancellation": {
              "deadline": "2020-09-10T09:30:00+05:30"
            }
          }
        }
      ],"self": "https://test.api.amadeus.com/v2/shopping/hotel-offers/by-hotel?hotelId=HXNYC432"
    },"hotelId": "BWNYC133","chainCode": "BW","dupeId": "700101379","name": "Best Western Bowery Hanbee Hotel","latitude": 40.7184,"longitude": -73.99518,"hoteldistance": {
          "distance": 1.0,"address": {
          "lines": [
            "231 GRAND STREET"
          ],"postalCode": "10013","cityName": "NEW YORK CITY","contact": {
          "phone": "+1 212 9251177","fax": "+1 212 9255533","email": "33133@hotel.bestwestern.com"
        },"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","FEMA_FIRE_SAFETY_COMPLIANT","HANDICAP_FAC","WAKEUP_SERVICE","CRIBS_AVAILABLE"
        ],"media": [
          {
            "uri": "http://uat.multimediarepository.testing.amadeus.com/cmr/retrieve/hotel/A15115741A8747538ECDBB2AA76B7DE9","offers": [
        {
          "id": "MLX8YR77R7","rateCode": "SRS","commission": {
            "percentage": "10"
          },"room": {
            "type": "A1Q","text": "SENIOR RATE*CITIZENS 55YRS PLUS OR AARP ID\n1 QUEEN bed,mobility ACC,COMMASSIST,ROLL SHWR,\nNSMK,CONTINENTAL BREAKFAST"
            }
          },"base": "242.10","total": "281.31","variations": {
              "average": {
                "base": "242.10"
              },"base": "242.10"
                }
              ]
            }
          },"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中获取名称,描述和联系方式。请帮助我打扰这个指针。指针不会进入酒店的孩子内部。

解决方法

我将JObject用于json,它的工作方式如下:

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);
    }
}

在复制dynamic和cityname时可以解决您的问题。您应该注意模型可能遇到的其他问题。

1-如果json数据中有多行,则您只会得到最后一个城市名称。而且您将失去所有其他人

2-最好由@Marco在您的评论中指出,实际映射该json

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。