Разбор JSON вернулся из ASP.Net в Javascript - PullRequest
1 голос
/ 26 января 2012

Я пытаюсь отобразить координаты следующего текста JSON на Mapquest Map, вызвав метод ASP.net, который возвращает эту строку, но я не могу понять, как извлечь из нее широту и долготу.

{"d":"{\"results\":[{\"fullName\":\"Albert Pinto\",\"callType\":\"Other - See Comments\",\"comments\":\"He was not happy with our dealer\u0027 s service. Had to be pacified.\",\"geolatitude\":38.9661791,\"geolongitude\":-94.7185354,\"geolocation\":\"{\\\"places\\\":[{\\\"street1\\\":\\\"Bond St\\\",\\\"postalCode\\\":\\\"66214\\\",\\\"address\\\":\\\"8951 Bond St, Overland Park, KS 66214, , United States\\\",\\\"displayAddress\\\":\\\"8951 Bond St, Overland Park, KS 66214, , United States\\\",\\\"street\\\":\\\"Bond St\\\",\\\"countryCode\\\":\\\"US\\\",\\\"region2\\\":\\\"\\\",\\\"longitude\\\":\\\"-94.718535\\\",\\\"region1\\\":\\\"\\\",\\\"latitude\\\":\\\"38.966179\\\",\\\"country_code\\\":\\\"US\\\",\\\"country\\\":\\\"United States\\\",\\\"city\\\":\\\"Overland Park\\\"}],\\\"source\\\":{\\\"locationServicesEnabled\\\":true,\\\"hasCompass\\\":true,\\\"purpose\\\":\\\"Get Current Location\\\"},\\\"success\\\":true}\",\"address\":\"8951 Bond St, Overland Park, KS 66214, , United States\",\"createdAt\":\"2012-01-18T05:57:58.923Z\",\"updatedAt\":\"2012-01-18T05:57:58.923Z\",\"objectId\":\"cqJK1nF1sB\"}]}"}

Я часами гуглял и пробовал несколько разных подходов (пытаясь вернуть только массив Lat / Long из asp.net, пытаясь проанализировать JSON с помощью JQuery), но мой ограниченныйЗнание JavaScript, кажется, препятствует любому прогрессу.

Любая помощь или указатели будут с благодарностью.Вот как выглядит мой JavaScript до сих пор ...

    <script type="text/javascript">

            MQA.EventUtil.observe(window, 'load', function () {

                $.ajax({
                    url: "Default.aspx/SendAnSMSMessage",   // This method returns the JSON string
                    type: "POST", // data has to be POSTed
                    contentType: "application/json", // posting JSON content    
                    dataType: "text",
                    //dataType: "JSON",  // type of data is JSON (must be upper case!)
                    timeout: 10000,    // AJAX timeout
                    success: function (result) {
                        console.log(result.toString()); //The JSON string is copied from the console here..
                        alert(result);

//NOT SURE WHAT TO DO NEXT HERE TO EXTRACT LAT/LONG.

                        /*Create a new POI collection.*/
                        var sc = new MQA.ShapeCollection(), poi, latlng = { lat: 39.0, lng: -82.0 }, i;

                        /*Create additional POIs and add them to the shape collection.*/
                        for (i = 0; i < 5; i++) {
                            latlng.lat = latlng.lat + 0.01;
                            latlng.lng = latlng.lng - 0.01;

                            poi = new MQA.Poi(latlng);
                            sc.add(poi);
                        }

                        /*Construct an instance of MQA.TileMap with the shape collection in the map constructor.*/
                        window.map = new MQA.TileMap({
                            elt: document.getElementById('map'),
                            collection: sc,
                            bestFitMargin: 100
                        });


                    },
                    error: function (xhr, status) {
                        alert(status + " - " + xhr.responseText);
                    }
                });

            });

        </script>

Вот код ASP.Net, который вызывает REST API.

[WebMethod] public static string SendAnSMSMessage() 
{ 
var httpWebRequest = (HttpWebRequest)WebRequest.Create("//myurl"); 
httpWebRequest.ContentType = "application/json";
httpWebRequest.Credentials = new NetworkCredential("name", "pwd"); 
httpWebRequest.Method = "GET"; 
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
{
var responseText = streamReader.ReadToEnd(); 
return responseText;} 
}

Ответы [ 5 ]

1 голос
/ 28 января 2012

Попробовав несколько разных способов выяснить, почему мой JavaScript не смог перебрать массив результатов для подробностей широты / долготы, я отказался и переместил всю логику отображения на серверную часть, используя элемент управления Reimers asp.net.*

Этот ТАК пост был особенно полезен ... Вот как выглядит моя страница asp.net ..

<body>
    <form id="form2" runat="server">

    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
        Text="Update Locations" />
    <br /> 

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <Reimers:Map ID="Map1" runat="server" Width="800" Height="600" DefaultMapType="Normal" Zoom="7">            
            <Center Latitude="51.477" Longitude="0.0" /> 
            </Reimers:Map>
                <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" 
                    GridLines="None">
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                    <EditRowStyle BackColor="#999999" />
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <SortedAscendingCellStyle BackColor="#E9E7E2" />
                    <SortedAscendingHeaderStyle BackColor="#506C8C" />
                    <SortedDescendingCellStyle BackColor="#FFFDF8" />
                    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                </asp:GridView>  
                <br />
        </ContentTemplate>

    </asp:UpdatePanel>
    </form>
</body>

и вот как работает код позади ...

 public void ParseJson(string jsonText)
    {
        JObject o = JObject.Parse(jsonText);
        JArray result = (JArray)o["results"];
        GridView1.DataSource = result;
        GridView1.DataBind();

        Double[,] strLocation = new Double[result.Count, 3];
        Reimers.Google.Map.Marker[] markers = new Reimers.Google.Map.Marker[result.Count];

        var centerLatLng = new Reimers.Google.Map.LatLng();

        for (int i = 0; i < result.Count; i++)
        {
            centerLatLng.Latitude = Convert.ToDouble(result[i]["geolatitude"].ToString());
            centerLatLng.Longitude = Convert.ToDouble(result[i]["geolongitude"].ToString());
            markers[i] = new Reimers.Google.Map.Marker(centerLatLng);
            markers[i].Title = result[i]["fullName"].ToString() + " - " + result[i]["callType"].ToString() +" : " + result[i]["comments"];
            Map1.Overlays.Add(markers[i]);

        }
        Map1.Center = markers[0].Point;
        var centerLatLng = new Reimers.Google.Map.LatLng();
        centerLatLng.Latitude = strLocation[1, 0];
        centerLatLng.Longitude = strLocation[1, 1];

        var marker = new Reimers.Google.Map.Marker(centerLatLng);
        Map1.Overlays.Add(marker);
    }
0 голосов
/ 26 января 2012

Взгляните на использование популярного JSON-парсера Дугласа Крокфорда . Мне нравится его использовать, потому что он использует собственный анализатор JSON браузера, если он доступен.

Кроме того, ASP.NET возвращает JSON в качестве обернутого объекта по соображениям безопасности . Следовательно, вы заметите JSON, завернутый в d parameter. Затем вы бы проанализировали JSON в вашем успешном обратном вызове, как

// Parse the JSON result
result = JSON.parse(result);
if (result && result.hasOwnProperty("d"))
    result = result.d;

и получите доступ к широте и долготе, используя

latlng = { lat: results[0].geolocation.places[0].latitude, lng: results[0].geolocation.places[0].longitude }

Вы также можете настроить глобальный jQuery AJAX-конвертер , чтобы проанализировать JSON перед выполнением вашего успешного обратного вызова. Что-то вроде

$.ajaxSetup({
    converters: { "text json": function (jsonData) {
            var result = JSON.parse(jsonData);

            if (result && result.hasOwnProperty("d"))
                result = result.d;

            return result;
        }
    }
});

Теперь при вашем обратном вызове вы просто получите доступ к нужным данным, как показано ранее.

0 голосов
/ 26 января 2012

Используйте $.parseJSON для анализа строки json, полученной в обработчике успеха ajax.Это даст вам объект JSON.Используя этот объект, вы можете легко получить доступ к широте и долготе.Попробуйте это.

success: function (result) {
    //The JSON string is copied from the console here..
    console.log(result.toString()); 
    result = $.parseJSON(result);

    /*Create a new POI collection.*/
    var sc = new MQA.ShapeCollection(), poi, 
        latlng = { lat: result.d.results[0].geolocation.places[0].latitude, 
                   lng: result.d.results[0].geolocation.places[0].longitude }, 
        i;

    /*Create additional POIs and add them to the shape collection.*/
    for (i = 0; i < 5; i++) {
       latlng.lat = latlng.lat + 0.01;
       latlng.lng = latlng.lng - 0.01;

       poi = new MQA.Poi(latlng);
       sc.add(poi);
    }

    /*Construct an instance of MQA.TileMap with the shape collection 
    in the map constructor.*/
    window.map = new MQA.TileMap({
       elt: document.getElementById('map'),
       collection: sc,
       bestFitMargin: 100
    });
},
0 голосов
/ 26 января 2012

Вызов веб-служб asp.net немного отличается.

Вам необходимо установить для dataType вашего вызова ajax значение json, а затем проанализировать result.d, а не result.

0 голосов
/ 26 января 2012

Как вы возвращаете свой объект JSON в методе ASp.Net, кажется, что вы возвращаете его в виде строки. Если вы возвращаете его таким образом, у вас не будет проблем с доступом к свойствам этого объекта в сценарии Java.

return Jason(yourObject)

тогда вы можете получить доступ к свойствам этого объекта в javascript следующим образом:

success: function (result) {
            alert(result.latitude);
...