• json字串转换成泛型类


    webrequst发送到指定的url

    using System;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using System.Net;
    using System.Text;
    using System.IO;
    
    /// <summary>
    ///simsimi 的摘要说明
    /// </summary>
    public class simsimi
    {
        public simsimi()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //string pageHtml = SendDataByGET("htp://www.simsimi.com/func/req?msg=" + msg + "!&lc=ch");
            //
        }
        public string ReturnStr(string msg)
        {
            return ReturnStr(msg, "Re_txt");
        }
        public string ReturnStr(string msg,string act)
        {
            string pageHtml = SendDataByGET("http://124.172.174.141/Handler1.ashx?msg=" + msg + "&act=" + act);
            pageHtml = "[" + pageHtml + "]";
            WebPageBase wb = new WebPageBase(); wb.WriteTxt(pageHtml);
            List<SiriResult> _List = JsonConvert.DeserializeObject<List<SiriResult>>(pageHtml);
            string re = "";
            foreach (SiriResult c in _List)
            {
                re = c.Response;
            }
            return re;
        }
        #region 同步通过GET方式发送数据
        /// <summary>
        /// 通过GET方式发送数据
        /// </summary>
        /// <param name="Url">url</param>
        /// <param name="postDataStr">GET数据</param>
        /// <param name="cookie">GET容器</param>
        /// <returns></returns>
        public string SendDataByGET(string Url)
        {
            string host = "http://124.172.174.141";
            WebRequest webRequest = WebRequest.Create(Url);
            HttpWebRequest request = webRequest as HttpWebRequest;
    
           //设置cookie
            CookieContainer cc = new CookieContainer();
            cc.Add(new Uri(host), new Cookie("JSESSIONID", "FC50E1B413D61FF258ED76121D15DBC8"));
            cc.Add(new Uri(host), new Cookie("__utma", "119922954.1431887846.1365044080.1365044080.1365044080.1"));
            cc.Add(new Uri(host), new Cookie("__utmb", "119922954.3.9.1365044144105"));
            cc.Add(new Uri(host), new Cookie("__utmc", "119922954"));
            cc.Add(new Uri(host), new Cookie("__utmz", "119922954.1365044080.1.1.utmcsr=tieba.baidu.com|utmccn=(referral)|utmcmd=referral|utmcct=/p/2166507443"));
            cc.Add(new Uri(host), new Cookie("sagree", "true"));
            request.CookieContainer = cc;
    
            request.Method = "GET";
            request.ContentType = "application/json; charset=utf-8";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20100101 Firefox/20.0";
            request.Referer = "    http://124.172.174.141/talk.htm";
            
    
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
    
            return retString;
        }
        #endregion
    
    
        /// <summary>
        /// 直接调用此方法,主动下发数据,返回是否成功的字符串
        /// </summary>
        /// <param name="JSONData">json格式数据</param>
        /// <param name="Url">要推送的url</param>
        /// <returns></returns>
        public string GetResponseData(string JSONData,string Url)
        {
                byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);  
                request.Method = "POST";  
                request.ContentLength = bytes.Length;  
                request.ContentType = "text/xml";  
                Stream reqstream = request.GetRequestStream();  
                reqstream.Write(bytes, 0, bytes.Length);  
      
                //声明一个HttpWebRequest请求  
                request.Timeout = 90000;  
                //设置连接超时时间  
                request.Headers.Set("Pragma", "no-cache");  
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();  
                Stream streamReceive = response.GetResponseStream();  
                Encoding encoding = Encoding.UTF8;  
      
                StreamReader streamReader = new StreamReader(streamReceive, encoding);  
                string  strResult = streamReader.ReadToEnd();  
                streamReceive.Dispose();  
                streamReader.Dispose();  
      
                return strResult;  
            }  
    }
    View Code

    json字符串处理类

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Newtonsoft.Json;
    using System.Reflection;
    using System.IO;
    using Newtonsoft.Json.Linq;
    
    /// <summary>
    ///JsonConvert 的摘要说明
    /// </summary>
    public class JsonToList<T>
    {
        public JsonToList()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }   
    
        public List<T> ToList(string jsonString)
        {
            List<T> list = new List<T>();
            List<string> li = JonsArr(jsonString);
            foreach (string s in li)
            {
                T t = (T)jsonToObject(s, typeof(T));
                list.Add(t);
            }
            return list;
        }
    
        /// <summary>
        /// 将{""name"":""zhang"",""age"":""19""},{""name"":""d打发"",""age"":""19""},{""name"":""阿凡达"",""age"":""19""}";格式
        /// 的字符串拆解,形成值对数组,加到list
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static List<string> JonsArr(string jsonString)
        {
            List<string> li = new List<string>();
            string s = jsonString.Replace(" ", "").Replace("},", "$");
            string[] strArr = s.Split('$');
            foreach (string str in strArr)
            {
                if (!string.IsNullOrEmpty(str))
                {
                    string s1 = str.Replace(""", "").Replace("}", "").Replace("{", "").Replace("
    ","").Replace("
    ","");
                    li.Add(s1);
                }
            }
            return li;
        }
        /// <summary>
        /// 反射取得单个对象
        /// </summary>
        /// <param name="jsonstr"></param>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public static object jsonToObject(string jsonstr, Type objectType)//传递两个参数,一个是json字符串,一个是要创建的对象的类型
        {
            string[] jsons = jsonstr.Split(new char[] { ',' });//将json字符串分解成 “属性:值”数组
            for (int i = 0; i < jsons.Length; i++)
            {
                jsons[i] = jsons[i].Replace(""", "");
            }//去掉json字符串的双引号
            object obj = System.Activator.CreateInstance(objectType); //使用反射动态创建对象
            //object obj = System.Activator.CreateInstance(typeof(stu)); //使用反射动态创建对象
            PropertyInfo[] pis = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);//获得对象的所有public属性
    
            if (pis != null)//如果获得了属性
                foreach (PropertyInfo pi in pis)//针对每一个属性进行循环
                {
                    for (int i = 0; i < jsons.Length; i++)//检查json字符串中的所有“属性:值”类表
                    {
                        if (jsons[i].Split(new char[] { ':' })[0] == pi.Name)//如果对象的属性名称恰好和json中的属性名相同
                        {
                            Type proertyType = pi.PropertyType; //获得对象属性的类型
                            pi.SetValue(obj, Convert.ChangeType(jsons[i].Split(new char[] { ':' })[1], proertyType), null);
                            //将json字符串中的字符串类型的“值”转换为对象属性的类型,并赋值给对象属性
                        }
                    }
                }
            return obj;
        }
    }
    View Code

    调用方法

     String jsonText = @"{""name"":""yy"",""age"":""19""},{""name"":""77"",""age"":""19""},{""name"":""阿凡达"",""age"":""19""}";       
            JsonToList<stu> jt = new JsonToList<stu>();
            List<stu> li = jt.ToList(jsonText);

    主动发送微信内容范例

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Newtonsoft.Json;
    using System.Reflection;
    using System.IO;
    using Newtonsoft.Json.Linq;
    
    
    public partial class test : WebPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            simsimi ss = new simsimi();
            JSONData jso = new JSONData();
            jso.Access_Token = "_ocC5n0Y4hYeZkE69xdthP_B8ic42JttWc8L5BamccxJw5d2nAdd8jPBZbRrigERbKoUCLsXS47WT73UkxlRplF7GBZaN5LhFvicGZq9bODyy2bxqESbSlnyruHU-xosa0Gcm1rbjoCZI7XWz5004A";
            jso.ToUser = "ocsmquGIU2GK7oQWTiUtBpGub64k";
    
            string title = "主题骑车比赛aaaa";
            string desc = "一下是详细介绍";
            string msg = "打球吧1146";
            string media_id = "i78Xd2EzMd-vCEOLOYY4ugtEmN94eZgAJrSUK2WADzgq5ZVER9zr1xtwXriJCZ_C";
    
            jso.JsonParaMedia = string.Format(@"{{""title"":""{0}"",""desc"":""{1}"""",""media_id"":""{2}"""",""msg"":""{3}""""""}}", title, desc, media_id, msg);
    
            string url = "http://test";
            string picurl = "http://imag";
            for (int i = 1; i < 10; i++)
            {
                jso.JsonParaNews += string.Format(@"{{""title"":""{0}"",""description"":""{1}"",""url"":""{2}"",""picurl"":""{3}""}},", title + i.ToString(), desc + i.ToString(), url + i.ToString(), picurl + i.ToString());
            }
    
            string s_bakc = ss.GetResponseData(jso.JsonDataString(JSONData.SendType.news), jso.Url);
            base.WriteTxt(s_bakc);
            Response.Write(s_bakc);
    
            //String jsonText = @"{""name"":""yy"",""age"":""19""},{""name"":""77"",""age"":""19""},{""name"":""阿凡达"",""age"":""19""}";       
            //JsonToList<stu> jt = new JsonToList<stu>();
            //List<stu> li = jt.ToList(jsonText);
    
    
    
    
            /*          推送文本        
            string JSONData = "{ "touser": "ocsmquGIU2GK7oQWTiUtBpGub64k",     "msgtype": "text",     "text": {        "content": "33"    }}";
            string Url = @"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=7QqKQ5bynTsZ0u4crNuEs6pVVJca-ZiQOibppGDDkgG_ytjAefWXdVk4X619c5mrPepfuMcmjGAUTej5SLNQU4DVydPXVwb9ZWFtbhTHc5RjPTuOGTa2LwJulmJ2-V5eEaY0X57Ikg0_Kpa8IQob8A";
            string s_bakc = ss.GetResponseData(JSONData,Url);
            base.WriteTxt(s_bakc);*/
    
            /*          推送图片        
            string JSONData = "{ "touser": "ocsmquGIU2GK7oQWTiUtBpGub64k",     "msgtype": "image",     "image": {      "media_id":"xj8VZqQG14KcEHUsPa95zi1obtucOoU_OU6Tf5W1QkBLQIsof7XXxS8QHOgIl1tq"   }}";
            string Url = @"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=7QqKQ5bynTsZ0u4crNuEs6pVVJca-ZiQOibppGDDkgG_ytjAefWXdVk4X619c5mrPepfuMcmjGAUTej5SLNQU4DVydPXVwb9ZWFtbhTHc5RjPTuOGTa2LwJulmJ2-V5eEaY0X57Ikg0_Kpa8IQob8A";
            string s_bakc = ss.GetResponseData(JSONData, Url);
            base.WriteTxt(s_bakc);
            Response.Write(s_bakc);*/
    
            /*          推送菜单       */
            //string JSONData =  "{     "button":[     {              "type":"click",          "name":"今日歌曲",          "key":"V1001_TODAY_MUSIC"      },      {           "type":"click",           "name":"歌手简介",           "key":"V1001_TODAY_SINGER"      },      {           "name":"菜单",           "sub_button":[           {                   "type":"view",               "name":"搜索",               "url":"http://www.soso.com/"            },            {               "type":"view",               "name":"视频",               "url":"http://v.qq.com/"            },            {               "type":"click",               "name":"赞一下我们",               "key":"V1001_GOOD"            }]       }] }";
            //string Url = @"https://api.weixin.qq.com/cgi-bin/menu/create?access_token=I8UUyLt5e8EUxZvcrcvEpf2kLOjCZ0x3ZAbzIueR80XvGIgDXWb4czhL2yzhsMyoh0ju7RVRUBjF1M16N-9XykbHiGgwa6s9-o8BhnwYCNfHcK2WGXkrUlZrOMHdpuOYcx5MiD7UNF0lTB1lZTJ1iA";
            //string s_bakc = ss.GetResponseData(JSONData, Url);
            //base.WriteTxt(s_bakc);
            //Response.Write(s_bakc);
    
    
    
    
    
        }
    }
    View Code

    注意:只能值对 jsonText格式的json的字符串进行处理,再复杂点的,就需要改写类中的方法了

    使用时,请引用dll Newtonsoft.Json_2013_12_26_19_23.rar

  • 相关阅读:
    vps安装wordpress遇到的问题(lnmp)
    RING0,RING1,RING2,RING3
    CentOS 下配置CUPS
    怎样解决VS2013模块对于SAFESEH 映像是不安全的
    【转】VC6.0打开或者添加工程文件崩溃的解决方法
    QWidget QMainWindow QDialog 三个基类的区别
    在C语言中,double、long、unsigned、int、char类型数据所占字节数
    拷贝构造函数
    “浅拷贝”与“深拷贝”
    常用软件列表
  • 原文地址:https://www.cnblogs.com/chusiping/p/3492946.html
Copyright © 2020-2023  润新知