我真的被这个问题困扰了 2 天,我怎样才能从深度嵌套的 json 对象中获取数据。
我在网上找到了一个json工具http://www.jsoneditoronline.org/ http://jsonformat.com/当您将 json 粘贴到其中时,它会显示所有对象数组等,因此我可以深入挖掘数据并获取我想要的信息。
当我调试代码并在以下位置设置断点时:foreach(rates.ToArray() 中的 JToken 数据) ,取决于我尝试的内容取决于我得到的错误,最后一个错误是。
Error converting value "@rateChange" to type 'Web.UI.Controllers.HomeController+RateInfo'.
Could not cast or convert from System.String to Web.UI.Controllers.HomeController+RateInfo.
非常感谢任何帮助。
我的类(class)
public class RateInfo
{
public string RateChange { get; set; }
public string Promo { get; set; }
public string PriceBreakdown { get; set; }
public bool NonRefundable { get; set; }
public string RateType { get; set; }
public int CurrentAllotment { get; set; }
public int? PromoId { get; set; }
public string PromoDescription { get; set; }
public string PromoType { get; set; }
}
代码
IList<JToken> rates = root["HotelListResponse"]["HotelList"]["HotelSummary"][0]["RoomRateDetailsList"]["RoomRateDetails"]["RateInfos"]["RateInfo"].Children().ToList();
IList<RateInfo> info = new List<RateInfo>();
foreach (JToken data in rates.ToArray())
{
RateInfo rateInfo = JsonConvert.DeserializeObject<RateInfo>(data.ToString());
info.Add(rateInfo);
}
JSON
{ "HotelListResponse" : { "HotelList" : { "@activePropertyCount" : "168",
"@size" : "2",
"HotelSummary" : [ { "@order" : "0",
"@ubsScore" : "360017",
"RoomRateDetailsList" : { "RoomRateDetails" : { "RateInfos" : { "@size" : "1",
"RateInfo" : { "@priceBreakdown" : "true",
"@promo" : "true",
"@rateChange" : "true",
"ChargeableRateInfo" : { "@averageBaseRate" : "68.62333",
"@averageRate" : "68.62333",
"@commissionableUsdTotal" : "205.87",
"@currencyCode" : "USD",
"@grossProfitOffline" : "14.06",
"@grossProfitOnline" : "27.44",
"@maxNightlyRate" : "77.87",
"@nightlyRateTotal" : "205.87",
"@total" : "205.87",
"NightlyRatesPerRoom" : { "@size" : "3",
"NightlyRate" : [ { "@baseRate" : "77.87",
"@promo" : "false",
"@rate" : "77.87"
},
{ "@baseRate" : "64.0",
"@promo" : "false",
"@rate" : "64.0"
},
{ "@baseRate" : "64.0",
"@promo" : "false",
"@rate" : "64.0"
}
]
}
},
"RoomGroup" : { "Room" : { "numberOfAdults" : 2,
"numberOfChildren" : 0,
"rateKey" : "f82ab843-49ee-481a-b53a-71647592b183"
} },
"currentAllotment" : 0,
"nonRefundable" : true,
"promoDescription" : "Advance Purchase Special - non-refundable",
"promoId" : 200827770,
"promoType" : "Standard",
"rateType" : "MerchantStandard"
}
},
"ValueAdds" : { "@size" : "1",
"ValueAdd" : { "@id" : "2048",
"description" : "Free Wireless Internet"
}
},
"expediaPropertyId" : 3084588,
"maxRoomOccupancy" : 3,
"minGuestAge" : 0,
"propertyAvailable" : true,
"propertyRestricted" : false,
"quotedRoomOccupancy" : 2,
"rateCode" : 200371945,
"roomDescription" : "Standard Room with King size bed",
"roomTypeCode" : 477014
} },
"address1" : "Stone Cellar Road",
"address2" : "High Usworth Newcastle",
"airportCode" : " ",
"amenityMask" : 18063491,
"city" : "Washington",
"confidenceRating" : 90,
"countryCode" : "GB",
"deepLink" : "http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=340461&mode=2&numberOfRooms=1&room-0-adult-total=2&room-0-child-total=0&arrivalMonth=11&arrivalDay=12&departureMonth=11&departureDay=15&showInfo=true&locale=en_US¤cyCode=USD",
"highRate" : 77.870000000000005,
"hotelId" : 340461,
"hotelInDestination" : true,
"hotelRating" : 3,
"latitude" : 54.922739999999997,
"locationDescription" : "Near Washington Old Hall",
"longitude" : -1.5342899999999999,
"lowRate" : 64,
"name" : "Mercure Newcastle George Washington Hotel Golf and Spa",
"postalCode" : "NE37 1PH",
"propertyCategory" : 1,
"proximityDistance" : 1.4710813,
"proximityUnit" : "MI",
"rateCurrencyCode" : "USD",
"shortDescription" : "<p><b>Location. </b> <br />Mercure Newcastle George Washington Hotel Golf and Spa is a business-friendly hotel located in Washington, close to Washington Old Hall, Angel of the North, and WWT",
"supplierType" : "E",
"thumbNailUrl" : "/hotels/4000000/3090000/3084600/3084588/3084588_84_t.jpg",
"tripAdvisorRating" : 3.5,
"tripAdvisorRatingUrl" : "http://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/3.5-12345-4.gif",
"tripAdvisorReviewCount" : 215
},
{ "@order" : "1",
"@ubsScore" : "258461",
"RoomRateDetailsList" : { "RoomRateDetails" : { "RateInfos" : { "@size" : "1",
"RateInfo" : { "@priceBreakdown" : "true",
"@promo" : "false",
"@rateChange" : "true",
"ChargeableRateInfo" : { "@averageBaseRate" : "54.83667",
"@averageRate" : "54.83667",
"@commissionableUsdTotal" : "164.51001",
"@currencyCode" : "USD",
"@grossProfitOffline" : "11.69",
"@grossProfitOnline" : "22.38",
"@maxNightlyRate" : "63.47",
"@nightlyRateTotal" : "164.51001",
"@total" : "164.51",
"NightlyRatesPerRoom" : { "@size" : "3",
"NightlyRate" : [ { "@baseRate" : "50.52",
"@promo" : "false",
"@rate" : "50.52"
},
{ "@baseRate" : "50.52",
"@promo" : "false",
"@rate" : "50.52"
},
{ "@baseRate" : "63.47",
"@promo" : "false",
"@rate" : "63.47"
}
]
}
},
"RoomGroup" : { "Room" : { "numberOfAdults" : 2,
"numberOfChildren" : 0,
"rateKey" : "f82ab843-49ee-481a-b53a-71647592b183"
} },
"currentAllotment" : 0,
"nonRefundable" : true,
"rateType" : "MerchantStandard"
}
},
"expediaPropertyId" : 901118,
"maxRoomOccupancy" : 2,
"minGuestAge" : 0,
"propertyAvailable" : true,
"propertyRestricted" : false,
"quotedRoomOccupancy" : 2,
"rateCode" : 200369466,
"roomDescription" : "Standard room with double bed - Book early & Save",
"roomTypeCode" : 162976
} },
"address1" : "Emerson Road",
"address2" : "District 5",
"airportCode" : "NCL",
"amenityMask" : 1507328,
"city" : "Washington",
"confidenceRating" : 85,
"countryCode" : "GB",
"deepLink" : "http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=207631&mode=2&numberOfRooms=1&room-0-adult-total=2&room-0-child-total=0&arrivalMonth=11&arrivalDay=12&departureMonth=11&departureDay=15&showInfo=true&locale=en_US¤cyCode=USD",
"highRate" : 63.469999999999999,
"hotelId" : 207631,
"hotelInDestination" : true,
"hotelRating" : 2,
"latitude" : 54.895090000000003,
"locationDescription" : "Near Washington Old Hall",
"longitude" : -1.55661,
"lowRate" : 50.520000000000003,
"name" : "Campanile Washington Newcastle Upon Tyne",
"postalCode" : "NE37 1LB",
"propertyCategory" : 1,
"proximityDistance" : 1.2526573000000001,
"proximityUnit" : "MI",
"rateCurrencyCode" : "USD",
"shortDescription" : "<p><b>Location. </b> <br />Campanile Washington Newcastle Upon Tyne is located in Washington, close to Washington Old Hall, Angel of the North, and WWT Washington Wetland Centre. Additional area",
"supplierType" : "E",
"thumbNailUrl" : "/hotels/1000000/910000/901200/901118/901118_20_t.jpg",
"tripAdvisorRating" : 3.5,
"tripAdvisorRatingUrl" : "http://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/3.5-12345-4.gif",
"tripAdvisorReviewCount" : 55
}
]
},
"cacheKey" : "4ef59f3e:13e1c495694:-6e28",
"cacheLocation" : "10.186.168.74:7301",
"cachedSupplierResponse" : { "@cachedTime" : "0",
"@candidatePreptime" : "100",
"@matchedCurrency" : "true",
"@matchedLocale" : "true",
"@otherOverheadTime" : "3",
"@supplierCacheTolerance" : "MED",
"@supplierRequestNum" : "118",
"@supplierResponseNum" : "2",
"@supplierResponseTime" : "468",
"@tpidUsed" : "5200"
},
"customerSessionId" : "0ABAA84A-59F3-E913-E1C2-495694906E33",
"moreResultsAvailable" : true,
"numberOfRoomsRequested" : 1
} }
=============================这段代码可以从摘要数组中获取数据========= ===
public class Hotelsummary
{
public string Name { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string CountryCode { get; set; }
public string ThumbNailUrl { get; set; }
public string ShortDescription { get; set; }
public double HotelRating { get; set; }
public double TripAdvisorRating { get; set; }
public string RateCurrencyCode { get; set; }
}
public IEnumerable<Hotelsummary> GetHotelsForLocationSearch()
{
var hotelDetails = GetHotelsFromEan.GetListOfHotels();
var root = JObject.Parse(hotelDetails.ToString());
IList<JToken> hotels = root["HotelListResponse"]["HotelList"]["HotelSummary"].Children().ToList();
IList<Hotelsummary> hotelsummaries = hotels.Select(result => JsonConvert
.DeserializeObject<Hotelsummary>(
result.ToString())).ToList();
return hotelsummaries;
}
但是一旦我尝试更深入地挖掘数据,我就无法获得我需要的数据
最佳答案
试试这个:
IList<JToken> rates = root["HotelListResponse"]["HotelList"]["HotelSummary"][0]["RoomRateDetailsList"]["RoomRateDetails"]["RateInfos"].Children().ToList();
编辑:
var rateInfo = json["HotelListResponse"]["HotelList"]["HotelSummary"][0]["RoomRateDetailsList"]["RoomRateDetails"]["RateInfos"]["RateInfo"];
var result =JsonConvert.DeserializeObject<RateInfo>( rateInfo .ToString() );
关于c# - 从深度嵌套的 json 对象获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16079116/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调