解析JSON从ASP.Net的Javascript返回 [英] Parsing JSON returned from ASP.Net in Javascript

查看:139
本文介绍了解析JSON从ASP.Net的Javascript返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过调用ASP.net方法,返回此字符串在Mapquest服务地图下面的JSON文本的坐标图,但我无法弄清楚如何从中提取的经度和纬度。


{D:{\\效果\\:[{\\全名\\:\\阿尔贝·平托\\,\\CALLTYPE \\:\\其他 - 看评论\\,\\评论\\:\\ 他并不高兴与我们的经销商\\ u0027的服务。必须是pacified.\\\",\\\"geolatitude\\\":38.9661791,\\\"geolongitude\\\":-94.7185354,\\\"geolocation\\\":\\\"{\\\\\\\"places\\\\\\\":[{\\\\\\\"street1\\\\\\\":\\\\\\\"Bond圣\\\\\\,\\\\\\邮政code \\\\\\:\\\\\\66214 \\\\\\,\\\\\\地址\\\\\\:\\\\\\8951邦德街,欧弗兰帕克,KS 66214,美国\\\\\\,\\\\\\displayAddress \\\\\\:\\\\\\8951邦德街,欧弗兰帕克,KS 66214,美国\\\\\\,\\\\\\街头\\ \\\\:\\\\\\键St\\\\\\\",\\\\\\\"country$c$c\\\\\\\":\\\\\\\"US\\\\\\\",\\\\\\\"region2\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"longitude\\\\\\\":\\\\\\\"-94.718535\\\\\\\",\\\\\\\"region1\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"latitude\\\\\\\":\\\\\\\"38.966179\\\\\\\",\\\\\\\"country_$c$c\\\\\\\":\\\\\\\"US\\\\\\\",\\\\\\\"country\\\\\\\":\\\\\\\"United美国\\\\\\,\\\\\\城市\\\\\\:\\\\\\陆上Park\\\\\\\"}],\\\\\\\"source\\\\\\\":{\\\\\\\"locationServicesEnabled\\\\\\\":true,\\\\\\\"hasCompass\\\\\\\":true,\\\\\\\"purpose\\\\\\\":\\\\\\\"Get当前位置\\\\\\},\\\\\\成功\\\\\\:真正} \\,\\地址\\:\\8951邦德街,欧弗兰帕克,KS 66214,美国States\\\",\\\"createdAt\\\":\\\"2012-01-18T05:57:58.923Z\\\",\\\"updatedAt\\\":\\\"2012-01-18T05:57:58.923Z\\\",\\\"objectId\\\":\\\"cqJK1nF1sB\\\"}]}\"}

我用Google搜索了几个小时,并尝试了几种不同的方法(试图只返回从asp.net纬度/多头排列,试图解析使用JQuery JSON),但我有限的JavaScript知识似乎阻碍任何进展。

任何帮助或指针将大大AP preciated。这里是我的JavaScript的样子至今....

 <脚本类型=文/ JavaScript的>            MQA.EventUtil.observe(窗口'负荷',函数(){                $阿贾克斯({
                    网址:Default.aspx的/ SendAnSMSMessage,//此方法返回JSON字符串
                    类型:POST,//数据已公布
                    的contentType:应用/ JSON,//张贴JSON内容
                    数据类型:TEXT,
                    //数据类型:JSON,//数据类型是JSON(必须大写!)
                    超时:10000,//超时AJAX
                    成功:函数(结果){
                        的console.log(result.toString()); // JSON字符串是从控制台复制在这里..
                        警报(结果);//不知道下一步该怎么做这里要提取的LAT / LONG。                        / *创建一个新的POI集合。* /
                        VAR SC =新MQA.ShapeCollection(),POI,经纬度= {纬度:39.0,经度:-82.0},我;                        / *创建额外的兴趣点,并把它们添加到收藏形状。* /
                        对于(I = 0; I&小于5;我++){
                            latlng.lat = latlng.lat + 0.01;
                            latlng.lng = latlng.lng - 0.01;                            POI =新MQA.Poi(经纬度);
                            sc.add(POI);
                        }                        / *构造MQA.TileMap的实例,形状集合中的地图构造函数。* /
                        window.map =新MQA.TileMap({
                            ELT:的document.getElementById(地图),
                            收藏:SC,
                            bestFitMargin:100
                        });
                    },
                    错误:功能(XHR,状态){
                        警报(状态+ - + xhr.responseText);
                    }
                });            });        < / SCRIPT>

下面是ASP.Net code调用REST API。

  [的WebMethod]公共静态字符串SendAnSMSMessage()
{
VAR的HttpWebRequest =(HttpWebRequest的)WebRequest.Create(// myurl);
httpWebRequest.ContentType =应用/ JSON;
httpWebRequest.Credentials =新的NetworkCredential(名,PWD);
httpWebRequest.Method =GET;
VAR HTT presponse =(HttpWebResponse)httpWebRequest.GetResponse();
使用(VAR的StreamReader =新的StreamReader(HTT presponse.GetResponseStream()))
{
变种的responseText = streamReader.ReadToEnd();
返回的responseText;}
}


解决方案

尝试几种不同的方式找出为什么我的JavaScript无法穿越的纬度/经度信息结果数组后,我放弃了,感动了整个映射使用赖默斯asp.net控制逻辑服务器端。

这SO职位是特别有用...
这里是我的asp.net页面的样子。

 <身体GT;
    <表ID =窗体2=服务器>    < ASP:按钮的ID =Button1的=服务器的onclick =的button1_Click
        文本=更新位置/>
    < BR />    < ASP:的ScriptManager ID =ScriptManager1=服务器>
    < / ASP:ScriptManager的>
    < ASP:的UpdatePanel ID =UpdatePanel1=服务器>
        <&的ContentTemplate GT;
            <赖默斯:地图ID =Map1的=服务器WIDTH =800HEIGHT =600DefaultMapType =正常缩放=7>
            <中心纬度=51.477经度=0.0/>
            < /赖默斯:地图>
                < ASP:GridView控件ID =GridView1=服务器的cellpadding =4前景色=#333333
                    网格线=无>
                    < AlternatingRowStyle背景色=白前景色=#284775/>
                    < EditRowStyle背景色=#999999/>
                    < FooterStyle背景色=#5D7B9DFONT-粗体=真前景色=白/>
                    < HeaderStyle背景色=#5D7B9DFONT-粗体=真前景色=白/>
                    < PagerStyle背景色=#284775前景色=白Horizo​​ntalAlign =中心/>
                    < RowStyle的BackColor =#F7F6F3前景色=#333333/>
                    < SelectedRowStyle背景色=#E2DED6FONT-粗体=真前景色=#333333/>
                    < SortedAscendingCellStyle背景色=#E9E7E2/>
                    < SortedAscendingHeaderStyle背景色=#506C8C/>
                    < SortedDescendingCellStyle背景色=#FFFDF8/>
                    < SortedDescendingHeaderStyle背景色=#6F8DAE/>
                < / ASP:GridView的>
                < BR />
        < /&的ContentTemplate GT;    < / ASP:的UpdatePanel>
    < /表及GT;
< /身体GT;

和这里是codebehind是如何工作的?

 公共无效ParseJson(字符串jsonText)
    {
        JObject O = JObject.Parse(jsonText);
        JArray结果=(JArray)O [成果];
        GridView1.DataSource =结果;
        GridView1.DataBind();        双[,] strLocation =新的双[result.Count,3];
        Reimers.Google.Map.Marker []标记=新Reimers.Google.Map.Marker [result.Count]        VAR centerLatLng =新Reimers.Google.Map.LatLng();        的for(int i = 0; I< result.Count;我++)
        {
            centerLatLng.Latitude = Convert.ToDouble(结果[I] [geolatitude]的ToString());
            centerLatLng.Longitude = Convert.ToDouble(结果[I] [geolongitude]的ToString());
            标记[I] =新Reimers.Google.Map.Marker(centerLatLng);
            标记[I] .title伪=结果[I] [全名]的ToString()+ - +结果[I] [CALLTYPE]的ToString()+:+结果[I] [意见。 ];
            Map1.Overlays.Add(标记[I]);        }
        Map1.Center =标记物[0] .Point;
        VAR centerLatLng =新Reimers.Google.Map.LatLng();
        centerLatLng.Latitude = strLocation [1,0];
        centerLatLng.Longitude = strLocation [1,1];        VAR的标记=新Reimers.Google.Map.Marker(centerLatLng);
        Map1.Overlays.Add(标记);
    }

I am trying to map the coordinates of the following JSON text on a Mapquest Map by calling an ASP.net method that returns this string, but I am unable to figure out how to extract the latitude and longitude from it.

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

I have googled for hours and tried several different approach (trying to return just a Lat/Long array from asp.net, trying to parse JSON using JQuery) but my limited knowledge of JavaScript seems to hinder any progress.

Any help or pointers will be greatly appreciated. Here is how my JavaScript looks like so far....

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

Here is the ASP.Net code that calls the 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;} 
}

解决方案

After trying several different ways to figure out why my JavaScript was not able to traverse the result array for lat/long details, I gave up and moved the entire mapping logic to server side using the Reimers asp.net control.

This SO post was especially useful... Here is how my asp.net page looks like..

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

and here is how the codebehind works...

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

这篇关于解析JSON从ASP.Net的Javascript返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆