asp.net 解析json数据

//Json所需引用
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

/// <summary>
/// JSON序列化和反序列化辅助类
/// </summary>
public class JsonHelper
{
    /// <summary>
    /// JSON序列化
    /// </summary>
    public static string JsonSerializer<T>(T t)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, t);
        string jsonString = Encoding.UTF8.GetString(ms.ToArray());
        ms.Close();
        return jsonString;
    }


    /// <summary>
    /// JSON反序列化
    /// </summary>
    public static T JsonDeserialize<T>(string jsonString)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        T obj = (T)ser.ReadObject(ms);
        return obj;
    }
}

//举例微信的登录的json数据解析
//微信Accesstoken信息
public class WxAccessTokenInfo
{
    public string access_token { get; set; }
    public string expires_in { get; set; }
    public string refresh_token { get; set; }
    public string openid { get; set; }
    public string scope { get; set; }
    public string unionid { get; set; }
}

//微信用户信息
public class WxUserInfo
{
    public string openid { get; set; }
    public string nickname { get; set; }
    public string sex { get; set; }
    public string province { get; set; }
    public string city { get; set; }
    public string country { get; set; }
    public string headimgurl { get; set; }
    public string privilege { get; set; }
    public string unionid { get; set; }
} 

public partial class WxLogin_Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //微信的json数据
        string JsonData = "微信的json数据";
        //解析数据
        WxAccessTokenInfo wxAccesstoken = JsonHelper.JsonDeserialize<WxAccessTokenInfo>(JsonData);
        //解析结束
        //调用wxAccesstoken内的成员变量即可
    }
}

展开阅读全文

没有更多推荐了,返回首页