从goo.gl Analytics访问JSON响应

时间:2011-07-13 19:17:54

标签: c# json

首先发布在这里。另外,我认为自己是一个非常非常低级的入门级c#/ asp.net / MSSQL开发人员,所以我的知识库是冬天松鼠坚果库的大小。

问题:无法从goo.gl analytics的JSON响应中提取多级(可能不是正确的术语)参数值。

我最近偶然发现谷歌提供的goo.gl网址缩短API并且喜欢它!这是我在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;         
}

现在,goo.gl还提供分析,例如创建时间,状态和短URL的点击次数。返回的JSON字符串采用以下格式:

{  
"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": { ... }  
    }
}

现在我可以从JSON响应中提取第一级参数值(id,status,longurl等),没问题。当我想从“分析”中提取“allTime”中的“shortUrlClicks”时,会出现问题。几天来我一直在谷歌的世界,但仍然没有结果。此外,尝试了各种序列化器,但仍然没有。我用来提取id,status和longurl的是:

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

解决方案!!!!!! * 解决方案!!!!!! * 解决方案!!!!!!

感谢您的回复。你完全没有使用正则表达式。在与我的“大师”进行了一些咨询后,我们发现了http://blogs.msdn.com/b/rakkimk/archive/2009/01/30/asp-net-json-serialization-and-deserialization.aspx

解决方案最终成为:

- 创建表示JSON层次结构的类

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

-next在响应流中,反序列化到层次结构中的最高元素(Analytics类),瞧!

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

1 个答案:

答案 0 :(得分:1)

查看Json.NET库,不要使用正则表达式进行解析。