5

特定の場所から位置情報を取得したいので、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 Corporation からの書面による明示的な許可がない限り、API にアクセスすることはできません。また、コンテンツおよび結果を使用、複製、または送信することはできません。","re​​sourceSets":[{"estimatedTotal":1,"resources":[{" __type":"場所:http://schemas.microsoft.com/search/local/ws/rest/v1","bbox":[47.253395080566406,-123.16571807861328,47.946159362792969,-121.50344085693359],"名前":"シアトル、 WA","点":{"種類":"点","座標":[47.603561401367188,-122.32943725585938]},"address":{"adminDistrict":"WA","adminDistrict2":"King Co.","countryRegion":"United States","formattedAddress":"Seattle, WA","locality": "Seattle"},"confidence":"High","entityType":"PopulatedPlace","geocodePoints":[{"type":"Point","coordinates":[47.603561401367188,-122.32943725585938],"calculationMethod": "Rooftop","usageTypes":["Display"]}],"matchCodes":["Good"]}]}],"statusCode":200,"statusDescription":"OK","traceId":"08bee37ecb714d7cb7e2783eb8f873a4 |LTSM000177|02.00.183.2300|LTSIPEVM000039"}adminDistrict":"WA","adminDistrict2":"King Co.","countryRegion":"United States","formattedAddress":"Seattle, WA","locality":"Seattle"},"confidence":" High","entityType":"PopulatedPlace","geocodePoints":[{"type":"Point","coordinates":[47.603561401367188,-122.32943725585938],"calculationMethod":"屋上","usageTypes":[" Display"]}],"matchCodes":["Good"]}]}],"statusCode":200,"statusDescription":"OK","traceId":"08bee37ecb714d7cb7e2783eb8f873a4|LTSM000177|02.00.183.2300|LTSIPEVM000039"}adminDistrict":"WA","adminDistrict2":"King Co.","countryRegion":"United States","formattedAddress":"Seattle, WA","locality":"Seattle"},"confidence":" High","entityType":"PopulatedPlace","geocodePoints":[{"type":"Point","coordinates":[47.603561401367188,-122.32943725585938],"calculationMethod":"Rooftop","usageTypes":[" Display"]}],"matchCodes":["Good"]}]}],"statusCode":200,"statusDescription":"OK","traceId":"08bee37ecb714d7cb7e2783eb8f873a4|LTSM000177|02.00.183.2300|LTSIPEVM000039"}countryRegion":"United States","formattedAddress":"Seattle, WA","locality":"Seattle"},"confidence":"High","entityType":"PopulatedPlace","geocodePoints":[{" type":"Point","coordinates":[47.603561401367188,-122.32943725585938],"calculationMethod":"Rooftop","usageTypes":["Display"]}],"matchCodes":["Good"]}]} ],"statusCode":200,"statusDescription":"OK","traceId":"08bee37ecb714d7cb7e2783eb8f873a4|LTSM000177|02.00.183.2300|LTSIPEVM000039"}countryRegion":"United States","formattedAddress":"Seattle, WA","locality":"Seattle"},"confidence":"High","entityType":"PopulatedPlace","geocodePoints":[{" type":"Point","coordinates":[47.603561401367188,-122.32943725585938],"calculationMethod":"Rooftop","usageTypes":["Display"]}],"matchCodes":["Good"]}]} ],"statusCode":200,"statusDescription":"OK","traceId":"08bee37ecb714d7cb7e2783eb8f873a4|LTSM000177|02.00.183.2300|LTSIPEVM000039"}entityType":"PopulatedPlace","geocodePoints":[{"type":"Point","coordinates":[47.603561401367188,-122.32943725585938],"calculationMethod":"Rooftop","usageTypes":["Display"]} ],"matchCodes":["良い"]}]}],"statusCode":200,"statusDescription":"OK","traceId":"08bee37ecb714d7cb7e2783eb8f873a4|LTSM000177|02.00.183.2300|LTSIPEVM000039"}entityType":"PopulatedPlace","geocodePoints":[{"type":"Point","coordinates":[47.603561401367188,-122.32943725585938],"calculationMethod":"Rooftop","usageTypes":["Display"]} ],"matchCodes":["良い"]}]}],"statusCode":200,"statusDescription":"OK","traceId":"08bee37ecb714d7cb7e2783eb8f873a4|LTSM000177|02.00.183.2300|LTSIPEVM000039"}statusDescription":"OK","traceId":"08bee37ecb714d7cb7e2783eb8f873a4|LTSM000177|02.00.183.2300|LTSIPEVM000039"}statusDescription":"OK","traceId":"08bee37ecb714d7cb7e2783eb8f873a4|LTSM000177|02.00.183.2300|LTSIPEVM000039"}

私の質問は次のとおりです。これは正しい方法ですか?また、データを取得するにはどうすればよいですか?

あなたが私を助けてくれることを願っています.私はすでにこの問題に多くの時間を費やしました.

- - -編集 - - -

今は JSON.net を使用していますが、Web サイトから取得したデータを文字列変数に解析する方法がわかりません。

私は次のことを試しました:

var json = new WebClient().DownloadString("url");

しかし、私はWindows Phoneで開発しているため、これは機能しません。

System.Net.WebClient には「DownloadString」の定義が含まれていません...

誰でも、Windows Phone アプリでこれを機能させるのを手伝ってくれます。

4

4 に答える 4

7

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

dynamicJson.net では、これらのクラスを宣言せずにキーワードを使用することもできます。

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]);
    }
}
于 2013-10-03T18:31:11.477 に答える
1

私はあなたがBINGマップを使用していることを知っていますが、Googleのソリューションもここにあります:

Google Map API リクエストと C# での DirectionsResponse の解析、URL の 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();

これが誰かを助けることを願っています。

于 2013-11-09T22:58:27.523 に答える