stephen99999
stephen99999

Reputation: 35

Accessing JSON response from goo.gl Analytics

First post here. Also, I would consider myself a very, very low, entry-level c#/asp.net/MSSQL developer so my knowledge base is the size of a squirrels nut vault for the winter.

Problem: Can't extract multi-level (may not be correct terminology) parameter values from JSON response from goo.gl analytics.

I recently stumbled across the goo.gl URL shortner API provided by google and love it! Here is the shortner code, which I found at http://www.jphellemons.nl/post/Google-URL-shortener-API-(googl)-C-sharp-class-C.aspx .

public static string Shorten(string url)         
{
    string key = "my_google_provided_API_key";
    string post = "{\"longUrl\": \"" + url + "\"}";             
    string shortUrl = url;             
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + key);               
    try            
    {                 
        request.ServicePoint.Expect100Continue = false;                 
        request.Method = "POST";                 
        request.ContentLength = post.Length;                 
        request.ContentType = "application/json";                 
        request.Headers.Add("Cache-Control", "no-cache");                   
        using (Stream requestStream = request.GetRequestStream())                 
        {                     
            byte[] postBuffer = Encoding.ASCII.GetBytes(post);                     
            requestStream.Write(postBuffer, 0, postBuffer.Length);                 
        }                   
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())                 
        {                     
            using (Stream responseStream = response.GetResponseStream())                     
            {                         
                using (StreamReader responseReader = new StreamReader(responseStream))                         
                {                             
                    string json = responseReader.ReadToEnd();                             
                    shortUrl = Regex.Match(json, @"""id"": ?""(?<id>.+)""").Groups["id"].Value;                         
                }                     
            }                 
        }             
    }             
    catch (Exception ex)             
    {                 
        // if Google's URL Shortner is down...                 
        System.Diagnostics.Debug.WriteLine(ex.Message);                 
        System.Diagnostics.Debug.WriteLine(ex.StackTrace);             
    }             
    return shortUrl;         
}

Now, goo.gl also provides analytics such as time created, status, and number of clicks on the short URL. The JSON string returned is in this format:

{  
"kind": "urlshortener#url",  
"id": value,  
"longUrl": value,  
"status": value,  
"created": value,  
"analytics": {    
"allTime": {      
            "shortUrlClicks": value,      
            "longUrlClicks": value,      
            "referrers": 
            [          
            {          
                "count": value,          
                "id": value        
            }, ...      
            ],      
            "countries": [ ... ],      
            "browsers": [ ... ],      
            "platforms": [ ... ]    
            },    
            "month": { ... },    
            "week": { ... },    
            "day": { ... },    
            "twoHours": { ... }  
    }
}

Now I can extract the first level of parameter values (id, status, longurl, etc) from the JSON response, no problem. The issue comes in when I want to extract, say "shortUrlClicks" from "allTime" from "analytics". I have scowered the world of google for days, and still no results. Also, have tried various serializers and still nothing. What I have been using to extract id, status, and longurl is:

protected void load_analytics(string shorturl)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?&shortUrl=" + shorturl+ "&projection=FULL");

        request.ServicePoint.Expect100Continue = false;
        request.Method = WebRequestMethods.Http.Get;
        request.Accept = "application/json";
        request.ContentType = "application/json; charset=utf-8";
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader responseReader = new StreamReader(responseStream))
                {
                    String json = responseReader.ReadToEnd();
                    String asdf = Regex.Match(json, @"""status"": ?""(?<status>.+)""").Groups["status"].Value; 
                }
            }
        }
}

SOLUTION FOUND!!!!!! *SOLUTION FOUND!!!!!!* SOLUTION FOUND!!!!!!

Thank you for the reply. You are absolutely right in not using the regex. After a little consulting with my "guru," we discovered http://blogs.msdn.com/b/rakkimk/archive/2009/01/30/asp-net-json-serialization-and-deserialization.aspx .

The solution ended up being :

-create the classes to represent the JSON hierarchy

public class Analytics
{
    public Alltime alltime = new Alltime();
}
public class Alltime
{
    public int ShortUrlClicks;
}

-next in the response stream, deserialize to the highest element in the hierarchy (Analytics class), and voila!

using (StreamReader responseReader = new StreamReader(responseStream))
                {
                    String json = responseReader.ReadToEnd();
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    //String asdf = Regex.Match(json, @"""status"": ?""(?<status>.+)""").Groups["status"].Value; 
                    Analytics p2 = js.Deserialize<Analytics>(json);
                    String fdas = p2.alltime.ShortUrlClicks.ToString();
                    //note how i traverse through the classes where p2 is Analytics 
                    //to alltime to ShortUrlClicks
               } //fdas yields "0" which is correct since the shorturl I tested has never been clicked

Upvotes: 1

Views: 1305

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56182

Look at Json.NET library, don't use regex for parsing.

Upvotes: 1

Related Questions