在 C# 中解析来自必应地图 API 的 JSON 代码
本文关键字:地图 API 代码 JSON | 更新日期: 2023-09-27 18:33:43
我使用Bing Map REST API,因为我想从一个单独的位置找出地理位置。Url 效果很好,但由于我第一次使用 JSON 代码,我真的不知道如何获得我想要的输出。
我尝试了以下方法:
string URL = "http://dev.virtualearth.net/REST/v1/Locations?countryRegion=&adminDistrict=&locality=Wien&postalCode=&addressLine=&userLocation=&userIp=&usermapView=&includeNeighborhood=&maxResults=&key=MY_KEY";
WebClient client = new WebClient();
client.OpenReadAsync(new Uri(URL, UriKind.Absolute));
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
private void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Point));
Point data = serializer.ReadObject(e.Result) as Point;
}
[DataContract]
public class Point
{
/// <summary>
/// Latitude,Longitude
/// </summary>
[DataMember(Name = "coordinates")]
public double[] Coordinates { get; set; }
}
当我在浏览器中输入链接时,这是我的回应:
{"authenticationResultCode":"ValidCredentials","brandLogoUri":"http://dev.virtualearth.net/Branding/logo_powered_by.png","copyright":"Copyright © 2013 Microsoft及其供应商。保留所有权利。未经Microsoft公司明确书面许可,不得以任何方式访问此 API,也不得以任何方式使用、复制或传输内容和任何结果。","resourceSets":[{"estimatedTotal":1,"resources":[{"__type":"Location:http://schemas.microsoft.com/search/local/ws/rest/v1","bbox":[47.253395080566406,-123.16571807861328,47.946159362792969,-121.50344085693359],"name":"西雅图,华盛顿","point":{"type":"点","坐标":[47.603561401367188,-122.32943725585938]},"地址":{"adminDistrict":"WA","adminDistrict2":"King Co.","countryRegion":"美国","formattedAddress":"Seattle,WA","locality":"Seattle"},"confidence":"High","entityType":"PopulatedPlace","geocodePoints":[{"type":"Point","坐标":[47.603561401367188,-122.32943725585938],"computeMethod":"Rooftop","usageTypes":["Display"]}],"matchCodes":["Good"]}]}],"statusCode":200,"statusDescription":"OK","traceId":"08BEE37ECB714d7cb7e2783eb8f873a4|LTSM000177|02.00.183.2300|LTSIPEVM000039"}
我现在的问题是:这是正确的方法吗?我如何获取数据?
希望你能帮助我,我已经花了很多时间解决这个问题。
-----编辑-----
现在我使用 JSON.net,但我不知道如何将我从网站获得的数据解析为字符串变量。
我尝试了以下方法:
var json = new WebClient().DownloadString("url");
但这行不通,因为我是在Windows Phone上开发的。
System.Net.WebClient 不包含"DownloadString"的定义...
任何人都可以帮助我让它适用于Windows Phone应用程序。
使用 json 时,我更喜欢 Json.Net。声明必要的类后,此代码是
var root = JsonConvert.DeserializeObject<RootObject>(json);
foreach (var rs in root.resourceSets)
{
foreach (var r in rs.resources)
{
Console.WriteLine(r.point.coordinates[0] + " , " + r.point.coordinates[1]);
}
}
您可以使用此站点将 json 转换为具体类
public class Point
{
public string type { get; set; }
public List<double> coordinates { get; set; }
}
public class Address
{
public string adminDistrict { get; set; }
public string adminDistrict2 { get; set; }
public string countryRegion { get; set; }
public string formattedAddress { get; set; }
public string locality { get; set; }
}
public class GeocodePoint
{
public string type { get; set; }
public List<double> coordinates { get; set; }
public string calculationMethod { get; set; }
public List<string> usageTypes { get; set; }
}
public class Resource
{
public string __type { get; set; }
public List<double> bbox { get; set; }
public string name { get; set; }
public Point point { get; set; }
public Address address { get; set; }
public string confidence { get; set; }
public string entityType { get; set; }
public List<GeocodePoint> geocodePoints { get; set; }
public List<string> matchCodes { get; set; }
}
public class ResourceSet
{
public int estimatedTotal { get; set; }
public List<Resource> resources { get; set; }
}
public class RootObject
{
public string authenticationResultCode { get; set; }
public string brandLogoUri { get; set; }
public string copyright { get; set; }
public List<ResourceSet> resourceSets { get; set; }
public int statusCode { get; set; }
public string statusDescription { get; set; }
public string traceId { get; set; }
}
Json.net 还允许您使用关键字dynamic
而无需声明任何这些类。
dynamic root = JsonConvert.DeserializeObject(json);
foreach (var rs in root.resourceSets)
{
foreach (var r in rs.resources)
{
Console.WriteLine(r.point.coordinates[0] + " , " + r.point.coordinates[1]);
}
}
Microsoft JSON 序列化程序/反序列化程序。
如果您不使用 ASP.NET 则需要包含 System.Web 和 System.Web.Extensions 引用;
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
Dictionary<string, object> json = (object[])javaScriptSerializer.DeserializeObject(text);
你不需要把它映射到一组类或结构,数组将被转换为object[],对象将被转换为字典。
若要查看生成的字典 json 的内容,可以使用 Visual Studio 检查器,或者直接访问内容,记住元素的映射方式。
例如,要访问您只需要的 brandLogoUri
(string)json["brandLogoUri"]
要循环资源集(即数组(,您需要执行以下操作
foreach(Dictionary<string,object> key in (Dictionary<string,object>)json["resourceSets"])
{
...do your stuff here...
}
当然,您的代码的可读性会降低,但如果将 json 映射到类太困难,或者如果您想动态执行一些测试,则它很有用
可以使用 http://json2csharp.com/生成自定义类。 将其包含在项目代码中。之后,将相同的 DataContractJsonSerializer 与新的 CustomClass 一起使用。
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(CustomClass));
CustomClass data = serializer.ReadObject(e.Result);
如果您使用VS2012,则有一个工具:http://blogs.msdn.com/b/webdev/archive/2012/12/18/paste-json-as-classes-in-asp-net-and-web-tools-2012-2-rc.aspx
你正在使用BING地图,但这也是一个谷歌解决方案:
Google Map API 请求并使用 C# 解析 DirectionsResponse ,将网址中的 json 更改为 xml并使用以下代码将结果转换为可用的 C# 泛型列表对象。
var url = String.Format("http://maps.googleapis.com/maps/api/directions/xml?...");
var result = new System.Net.WebClient().DownloadString(url);
var doc = XDocument.Load(new StringReader(result));
var DirectionsResponse = doc.Elements("DirectionsResponse").Select(l => new
{
Status = l.Elements("status").Select(q => q.Value).FirstOrDefault(),
Route = l.Descendants("route").Select(n => new
{
Summary = n.Elements("summary").Select(q => q.Value).FirstOrDefault(),
Leg = n.Elements("leg").ToList().Select(o => new
{
Step = o.Elements("step").Select(p => new
{
Travel_Mode = p.Elements("travel_mode").Select(q => q.Value).FirstOrDefault(),
Start_Location = p.Elements("start_location").Select(q => new
{
Lat = q.Elements("lat").Select(r => r.Value).FirstOrDefault(),
Lng = q.Elements("lng").Select(r => r.Value).FirstOrDefault()
}).FirstOrDefault(),
End_Location = p.Elements("end_location").Select(q => new
{
Lat = q.Elements("lat").Select(r => r.Value).FirstOrDefault(),
Lng = q.Elements("lng").Select(r => r.Value).FirstOrDefault()
}).FirstOrDefault(),
Polyline = p.Elements("polyline").Select(q => new
{
Points = q.Elements("points").Select(r => r.Value).FirstOrDefault()
}).FirstOrDefault(),
Duration = p.Elements("duration").Select(q => new
{
Value = q.Elements("value").Select(r => r.Value).FirstOrDefault(),
Text = q.Elements("text").Select(r => r.Value).FirstOrDefault(),
}).FirstOrDefault(),
Html_Instructions = p.Elements("html_instructions").Select(q => q.Value).FirstOrDefault(),
Distance = p.Elements("distance").Select(q => new
{
Value = q.Elements("value").Select(r => r.Value).FirstOrDefault(),
Text = q.Elements("text").Select(r => r.Value).FirstOrDefault(),
}).FirstOrDefault()
}).ToList(),
Duration = o.Elements("duration").Select(p => new
{
Value = p.Elements("value").Select(q => q.Value).FirstOrDefault(),
Text = p.Elements("text").Select(q => q.Value).FirstOrDefault()
}).FirstOrDefault(),
Distance = o.Elements("distance").Select(p => new
{
Value = p.Elements("value").Select(q => q.Value).FirstOrDefault(),
Text = p.Elements("text").Select(q => q.Value).FirstOrDefault()
}).FirstOrDefault(),
Start_Location = o.Elements("start_location").Select(p => new
{
Lat = p.Elements("lat").Select(q => q.Value).FirstOrDefault(),
Lng = p.Elements("lng").Select(q => q.Value).FirstOrDefault()
}).FirstOrDefault(),
End_Location = o.Elements("end_location").Select(p => new
{
Lat = p.Elements("lat").Select(q => q.Value).FirstOrDefault(),
Lng = p.Elements("lng").Select(q => q.Value).FirstOrDefault()
}).FirstOrDefault(),
Start_Address = o.Elements("start_address").Select(q => q.Value).FirstOrDefault(),
End_Address = o.Elements("end_address").Select(q => q.Value).FirstOrDefault()
}).ToList(),
Copyrights = n.Elements("copyrights").Select(q => q.Value).FirstOrDefault(),
Overview_polyline = n.Elements("overview_polyline").Select(q => new
{
Points = q.Elements("points").Select(r => r.Value).FirstOrDefault()
}).FirstOrDefault(),
Waypoint_Index = n.Elements("waypoint_index").Select(o => o.Value).ToList(),
Bounds = n.Elements("bounds").Select(q => new
{
SouthWest = q.Elements("southwest").Select(r => new
{
Lat = r.Elements("lat").Select(s => s.Value).FirstOrDefault(),
Lng = r.Elements("lng").Select(s => s.Value).FirstOrDefault()
}).FirstOrDefault(),
NorthEast = q.Elements("northeast").Select(r => new
{
Lat = r.Elements("lat").Select(s => s.Value).FirstOrDefault(),
Lng = r.Elements("lng").Select(s => s.Value).FirstOrDefault()
}).FirstOrDefault(),
}).FirstOrDefault()
}).FirstOrDefault()
}).FirstOrDefault();
我希望这会帮助某人。