c# - 无法从 JValue 转换为 JObject
问题描述
我有以下带有静态方法的类,
public static class RouteSerializer
{
public static string SerializeRouteInformation(string content)
{
RouteMapModel routeMapModel = new RouteMapModel();
List<RouteMapModel.end_location> endLocationList = new List<RouteMapModel.end_location>();
var obj = JObject.Parse(content);
string objRoutes = obj["routes"].ToString();
JArray routeArray = JArray.Parse(objRoutes);
JArray legArray = new JArray();
foreach (JObject item in routeArray)
{
string leg = item.GetValue("legs").ToString();
legArray.Add(leg);
}
JArray stepArray = new JArray();
foreach (JObject item in legArray)
{
string step = item.GetValue("steps").ToString();
stepArray.Add(step);
}
foreach(JObject item in stepArray)
{
string endLocation = item.GetValue("end_location").ToString();
var serializedEndLocation = JsonConvert.DeserializeObject<RouteMapModel.end_location>(endLocation);
endLocationList.Add(serializedEndLocation);
}
//... goes on
}
}
foreach
但是,正如它所说,我在第二个乞求时得到了一个错误Newtonsoft.Json.Linq.JValue cannot be assigned to Newtonsoft.Json.Linq.JObject
。但问题是,如果我在后面的条款中将项目类型从 JObject 更改为 JValue foreach
,我将无法访问.GetValue()
方法,因为 JValue 不包含一个。
下面是我正在播放的 JSON 字符串,
{ "geocoded_waypoints" : [
{
"geocoder_status" : "OK",
"place_id" : "ChIJ5cGzCGa4yhQRk-lsJUoyizk",
"types" : [ "street_address" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJb5VnEF64yhQRCrgps2g77jc",
"types" : [ "street_address" ]
}
],
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 40.990381,
"lng" : 29.0282547
},
"southwest" : {
"lat" : 40.9863897,
"lng" : 29.0216118
}
},
"copyrights" : "Harita verileri ©2019 Google",
"legs" : [
{
"distance" : {
"text" : "0,9 km",
"value" : 894
},
"duration" : {
"text" : "11 dakika",
"value" : 655
},
"end_address" : "Caferağa Mahallesi, Tuğlacı Eminbey Cd. No:5, 34710 Kadıköy/İstanbul, Türkiye",
"end_location" : {
"lat" : 40.9863897,
"lng" : 29.0218105
},
"start_address" : "Osmanağa Mahallesi, Serasker Cd. No:118, 34714 Kadıköy/İstanbul, Türkiye",
"start_location" : {
"lat" : 40.9893375,
"lng" : 29.028225
},
"steps" : [
{
"distance" : {
"text" : "8 m",
"value" : 8
},
"duration" : {
"text" : "1 dakika",
"value" : 5
},
"end_location" : {
"lat" : 40.9894537,
"lng" : 29.0282117
},
"html_instructions" : "\u003cb\u003eZiya Bey Sk.\u003c/b\u003e adlı yerden \u003cb\u003eSerasker Cd.\u003c/b\u003e hedefine \u003cb\u003ekuzey\u003c/b\u003e yönünde ilerleyin",
"polyline" : {
"points" : "kvdyFkqdpDGCMA?F"
},
"start_location" : {
"lat" : 40.9893375,
"lng" : 29.028225
},
"travel_mode" : "WALKING"
},
{
"distance" : {
"text" : "0,3 km",
"value" : 326
},
"duration" : {
"text" : "4 dakika",
"value" : 215
},
"end_location" : {
"lat" : 40.990381,
"lng" : 29.024582
},
"html_instructions" : "\u003cb\u003eSerasker Cd.\u003c/b\u003e yönünde \u003cb\u003esola\u003c/b\u003e dönün",
"maneuver" : "turn-left",
"polyline" : {
"points" : "awdyFiqdpDMxAKr@OjACP[vCEPC^Cf@CLAHENMZ@LQf@Qd@KZENSj@"
},
"start_location" : {
"lat" : 40.9894537,
"lng" : 29.0282117
},
"travel_mode" : "WALKING"
},
{
"distance" : {
"text" : "34 m",
"value" : 34
},
"duration" : {
"text" : "1 dakika",
"value" : 25
},
"end_location" : {
"lat" : 40.9901185,
"lng" : 29.0243691
},
"html_instructions" : "\u003cb\u003eMühürdar Cd.\u003c/b\u003e yönünde \u003cb\u003esola\u003c/b\u003e dönün",
"maneuver" : "turn-left",
"polyline" : {
"points" : "{|dyFszcpDHFHF^X"
},
"start_location" : {
"lat" : 40.990381,
"lng" : 29.024582
},
"travel_mode" : "WALKING"
},
{
"distance" : {
"text" : "8 m",
"value" : 8
},
"duration" : {
"text" : "1 dakika",
"value" : 5
},
"end_location" : {
"lat" : 40.990081,
"lng" : 29.0242851
},
"html_instructions" : "\u003cb\u003eMühürdar Cd.\u003c/b\u003e yönünde hafif \u003cb\u003esağa\u003c/b\u003e yönelin",
"maneuver" : "turn-slight-right",
"polyline" : {
"points" : "g{dyFiycpD?D?@?@@??@DB"
},
"start_location" : {
"lat" : 40.9901185,
"lng" : 29.0243691
},
"travel_mode" : "WALKING"
},
{
"distance" : {
"text" : "7 m",
"value" : 7
},
"duration" : {
"text" : "1 dakika",
"value" : 6
},
"end_location" : {
"lat" : 40.9900274,
"lng" : 29.0243112
},
"html_instructions" : "\u003cb\u003eMuvakkıthane Cd.\u003c/b\u003e konumunda \u003cb\u003esola\u003c/b\u003e dönün",
"maneuver" : "turn-left",
"polyline" : {
"points" : "_{dyFyxcpDDABA"
},
"start_location" : {
"lat" : 40.990081,
"lng" : 29.0242851
},
"travel_mode" : "WALKING"
},
{
"distance" : {
"text" : "0,4 km",
"value" : 352
},
"duration" : {
"text" : "4 dakika",
"value" : 259
},
"end_location" : {
"lat" : 40.987586,
"lng" : 29.0217648
},
"html_instructions" : "\u003cb\u003eMühürdar Cd.\u003c/b\u003e yönünde \u003cb\u003esağa\u003c/b\u003e dönün",
"maneuver" : "turn-right",
"polyline" : {
"points" : "uzdyF}xcpDhAz@pA|@pBtAHRJHRPPNPX\\d@BDHKfAlBDLDHDN@LBN"
},
"start_location" : {
"lat" : 40.9900274,
"lng" : 29.0243112
},
"travel_mode" : "WALKING"
},
{
"distance" : {
"text" : "63 m",
"value" : 63
},
"duration" : {
"text" : "1 dakika",
"value" : 51
},
"end_location" : {
"lat" : 40.987087,
"lng" : 29.0216118
},
"html_instructions" : "\u003cb\u003eMühürdar Cd.\u003c/b\u003e boyunca ilerlemek için \u003cb\u003esola\u003c/b\u003e dönün",
"maneuver" : "turn-left",
"polyline" : {
"points" : "mkdyF_icpDNBJ@J@TBJ?JADA@DDN"
},
"start_location" : {
"lat" : 40.987586,
"lng" : 29.0217648
},
"travel_mode" : "WALKING"
},
{
"distance" : {
"text" : "74 m",
"value" : 74
},
"duration" : {
"text" : "1 dakika",
"value" : 64
},
"end_location" : {
"lat" : 40.9864708,
"lng" : 29.0216118
},
"html_instructions" : "\u003cb\u003eMühürdar Cd.\u003c/b\u003e boyunca ilerlemek için \u003cb\u003esola\u003c/b\u003e dönün",
"maneuver" : "turn-left",
"polyline" : {
"points" : "ihdyFahcpDJEJAFALAH?VBj@F"
},
"start_location" : {
"lat" : 40.987087,
"lng" : 29.0216118
},
"travel_mode" : "WALKING"
},
{
"distance" : {
"text" : "22 m",
"value" : 22
},
"duration" : {
"text" : "1 dakika",
"value" : 25
},
"end_location" : {
"lat" : 40.9863897,
"lng" : 29.0218105
},
"html_instructions" : "\u003cb\u003eTuğlacı Eminbey Cd.\u003c/b\u003e yönünde \u003cb\u003esola\u003c/b\u003e dönün",
"maneuver" : "turn-left",
"polyline" : {
"points" : "mddyFahcpDNg@"
},
"start_location" : {
"lat" : 40.9864708,
"lng" : 29.0216118
},
"travel_mode" : "WALKING"
}
],
"traffic_speed_entry" : [],
"via_waypoint" : []
}
],
"overview_polyline" : {
"points" : "kvdyFkqdpDUEM`B{@hHQfBGXMZ@Lc@lAQj@Sj@HFHF^X?D?B@@DBDABAhAz@bErCHRJHd@`@n@~@BDHKlAzBJXD\\ZD`@DVADA@DDNJERCVAbAJNg@"
},
"summary" : "Serasker Cd. ve Mühürdar Cd.",
"warnings" : [
"Yürüyerek gitmek için yol tarifi beta özelliğinde mevcuttur. Dikkat – Bu rotada kaldırım veya yaya yolu olmayabilir."
],
"waypoint_order" : []
}
],
"status" : "OK"
}
我不喜欢反序列化整个对象,因为服务不会使用几乎所有这些属性,除了"legs"
,"steps"
和."end_location"
"steps"
解决方案
问题是您查询JObject obj
层次结构选定部分的代码反复来回转换JToken
为 JSON 字符串表示形式,并且在某一时刻,您无需重新解析JSON 字符串,而是将其用作字符串文字。
具体来说,问题出在以下代码上:
JArray legArray = new JArray();
foreach (JObject item in routeArray)
{
string leg = item.GetValue("legs").ToString();
legArray.Add(leg);
}
你在调用JArray.Add()
,但是这个方法有多个重载,那么调用的是哪一个呢?因为有一个隐式运算符 from string
toJToken
,所以发生的情况是使用隐式运算符将leg
字符串转换为JValue
字符串文字,然后将其添加到JArray
. 之后,以下代码因无效转换异常而失败,因为您添加的项目legArray
类型为JValue
not JObject
:
foreach (JObject item in legArray)
{
解决方案string
是简化您的代码并完全避免在和JToken
表示之间来回转换。以下代码可以解决问题:
var endLocationList = obj
.SelectTokens("routes[*].legs[*].steps[*].end_location")
.Select(t => t.ToObject<Location>())
.ToList();
使用类型
public class Location
{
public double Lat { get; set; }
public double Lng { get; set; }
}
笔记:
您可以
JToken
使用JToken.ToObject<T>()
. 这比将其格式化JToken
为字符串然后反序列化字符串更简单、更高效。JToken.SelectTokens()
允许使用JSONPath 语法查询 JSON 层次结构。这里
[*]
表示一个通配符,用于选择数组中的所有项目,特别是"routes"
和"legs"
数组"steps"
。有关详细信息,请参阅# JSONPath - JSON 的 XPath。
演示小提琴在这里。
推荐阅读
- sql - 从每组中仅选择顶行
- angular8 - 如何使用 angular8 在 iframe 上禁用视频播放器属性
- c++ - std::cspan 发生了什么?
- sublimetext3 - SublimeText 3 软件包安装错误
- c# - 如何将“XX,XXX”替换为“XX XXX”?
- javascript - 在选择器中转义反斜杠
- java - 如何在没有任何背景的情况下使用 android 启动器图标
- oracle - Sqlldr tab delim 文件加载问题
- angular - 通过在 typescript 中调用方法打开 bootstrap 4 模态
- java - NoSuchMethodError 当不直接调用方法,而是服务方法时