开发者

Parse a JSON query response string in ASP.NET

开发者 https://www.devze.com 2023-01-20 22:38 出处:网络
Hey guys I have the following code working which is sending a GET Request and receiving JSON Response.

Hey guys I have the following code working which is sending a GET Request and receiving JSON Response.

Now I can basically go

GetWeatherByLocation(53.3, -6.28);

and the method returns

{"status":"OK","url":"http://www.link.com/areas/rathfarnham-11","name":"Rathfarnham"}

I was now wondering how can I retrieve the values for

  • URL
  • Name

from the string returned

THanks a lot

Im using ASP.NET 2 this is my calling code

public static string GetWeatherByLocation(double lat, double lng)
{

    string formattedUri = String.Format(CultureInfo.InvariantCulture,

                          FindNearbyWeatherUrl, lat, lng);



    HttpWebRequest webRequest = GetWebRequest(formattedUri);

    HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

    string jsonResponse = string.开发者_运维百科Empty;

    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {

        jsonResponse = sr.ReadToEnd();

    }

    return jsonResponse;

}


Your calling code is in javascript, i guess. Just use the response as a javascript object, because the json format is a notation for a javascript object. You can access its properties directly:

var returningValue = {"status":"OK","url":"http://www.link.com/areas/rathfarnham-11","name":"Rathfarnham"} ;
alert(returningValue.status);
alert(returningValue.url);
alert(returningValue.name);

edit: if you want to parse json in .net you can see this question where somebody explains how to parse the object using JavaScriptSerializer from System.Web.Extensions.dll


edit 2: if your version of .net doesn't let you play with this .dll i'd recommend looking into json.net previous releases, notably the last 2.0 release. But you should have access to the dll since it appeared in .net 2.0, albeit in the AJAX framework if my memory is good...

It's possible to parse your object by hand, but i'd really recommend using a library instead. If you want to do it by hand, you're in a complex world...

0

精彩评论

暂无评论...
验证码 换一张
取 消