我是一名测试人员,正在学习 C# 和 REST 服务测试,这对我来说都是新的…… 我有一个像这样的 JSON 响应
{ "results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4223434,
"lng" : -122.0843689
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.42369238029149,
"lng" : -122.0830199197085
},
"southwest" : {
"lat" : 37.42099441970849,
"lng" : -122.0857178802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
并将其反序列化为对象,只需要几何/位置中的“lat”和“lng”
我的代码看起来像
JObject myMap = JObject.Parse(response.Content);
IList<JToken> mylist = myMap["results"][0]["geometry"].Children().ToList();`
IList<location> spots = new List<location>();
foreach (JToken spot in mylist)
{
Console.WriteLine("\nthe spots are :\t:"+ spot.ToString());
location somesopt = JsonConvert.DeserializeObject<location>(spot.ToString());
Console.WriteLine("\n the lat is :\t" + somesopt.lat.ToString());
Console.WriteLine("\n the lat is :\t" + somesopt.lng.ToString());
}
我的对象是…………
public class location
{
public double lat { get; set; }
public double lng { get; set; }
}
public class geopost
{
public location geometry;
}
问题是我总是在 json deseserializobject 处得到 JsonSerializationException 我尝试更改定义 mylist 的许多排列 但无法写入....我做错了什么..?
当在地址组件中对“Long_name”和“short_name”使用相同的代码结构时,它工作正常。我知道地址组件是数组,几何/位置是对象。但你如何处理它?</p>
最佳答案
我按照 DavidG 的建议做同样的事情,但我通过将 JSON 复制到剪贴板然后在 VS 上转到菜单 Edit
->Paste Special
->将 JSON 作为类粘贴
。
生成反序列化所需的类:
public class Rootobject
{
public Result[] results { get; set; }
public string status { get; set; }
}
public class Result
{
public Address_Components[] address_components { get; set; }
public string formatted_address { get; set; }
public Geometry geometry { get; set; }
public string place_id { get; set; }
public string[] types { get; set; }
}
(...)
同样的反序列化方法:
var data = JsonConvert.DeserializeObject<RootObject>(json);
关于c# - 使用 Newtonsoft.Json 反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39007437/