c# 利用結構體獲取json數據

最近作微信支付,要獲取用戶的openid,調用接口後返回的是json格式的數據,我想在c#後臺把數據逐一取出,網上查了查,找到如下方法:json

1.首先調用接口,要有一個post數據到指定url並返回數據的函數:c#

    protected string PostXmlToUrl(string url, string postData)
    {
        string returnmsg = "";
        using (System.Net.WebClient wc = new System.Net.WebClient())
        {
            returnmsg = wc.UploadString(url, "POST", postData);
        }
        return returnmsg;
    }

post的數據格式能夠是api

url的參數格式(a=1&b=2&c=3....)微信

xml格式(<xml>....</xml>)app

返回的數據格式由接口肯定。函數

2.方法調用:post

        string post_data = "appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        string requestData = PostXmlToUrl("https://api.weixin.qq.com/sns/oauth2/access_token", post_data);

微信這個接口返回的數據是json格式的,因此獲得的requestData就是一段json字符串:微信支付

{
   "access_token":"ACCESS_TOKEN",
   "expires_in":7200,
   "refresh_token":"REFRESH_TOKEN",
   "openid":"OPENID",
   "scope":"SCOPE"
}

返回的數據裏面有我須要的openid,接下來利用結構體把openid取出。先定義結構體:url

    public struct authorization
    {
        public string access_token { get; set; }  //屬性的名字,必須與json格式字符串中的"key"值同樣。
        public string expires_in { get; set; }
        public string refresh_token { get; set; }
        public string openid { get; set; }
        public string scope { get; set; }
    }

利用序列化數據的類JavaScriptSerializer將json數據轉化爲對象類型:spa

        JavaScriptSerializer js = new JavaScriptSerializer();   //實例化一個可以序列化數據的類
        authorization auth = js.Deserialize<authorization>(requestData);    //將json數據轉化爲對象類型並賦值給auth

這樣一轉化,對象auth裏面的4個屬性就會獲得相應的值,如此,我就獲取到了接口返回來的openid,就能夠在須要的地方使用它了:

        wxobPay.openid = auth.openid;
相關文章
相關標籤/搜索