在Javascript中解析从ASP.Net返回的JSON

时间:2012-01-26 03:32:12

标签: jquery asp.net json mapquest

我试图通过调用返回此字符串的ASP.net方法在Mapquest Map上映射以下JSON文本的坐标,但我无法弄清楚如何从中提取纬度和经度。

{"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\"}]}"}

我已经搜索了几个小时并尝试了几种不同的方法(尝试从asp.net返回一个Lat / Long数组,尝试使用JQuery解析JSON)但我对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>

以下是调用REST API的ASP.Net代码。

[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 个答案:

答案 0 :(得分:1)

在尝试了几种不同的方法来弄清楚为什么我的JavaScript无法遍历结果数组以获取lat / long细节之后,我放弃并使用Reimers asp.net控件将整个映射逻辑移动到服务器端。

This SO post was especially useful... 这是我的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);
    }

答案 1 :(得分:0)

使用$.parseJSON来解析您在ajax成功处理程序中获得的json字符串。它会给你一个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
    });
},

答案 2 :(得分:0)

调用asp.net Web服务略有不同。

您需要将ajax调用的dataType设置为'json',然后解析result.d,而不是结果。

success: function (result) {
  result = $.parseJSON(result.d);
  // now use result like normal, using result, not result.d like you listed in your example.
}

答案 3 :(得分:0)

看看道格拉斯·克罗克福德受欢迎的JSON parser。我喜欢使用它,因为它使用浏览器的原生JSON解析器(如果可用)。

此外,由于security原因,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 converter来解析JSON。像

这样的东西
$.ajaxSetup({
    converters: { "text json": function (jsonData) {
            var result = JSON.parse(jsonData);

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

            return result;
        }
    }
});

现在,在您的回调中,您只需访问前面显示的所需数据。

答案 4 :(得分:-1)

如何在ASp.Net方法中返回JSON对象,好像是将它作为字符串返回。如果你像这样返回它,那么在java脚本中访问该对象的属性就不会有问题。

return Jason(yourObject)

然后你可以在这样的javascript中访问那个对象属性,

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