zoukankan      html  css  js  c++  java
  • ASP.NET json数据的序列化与反序列化

            使用asp.net 做项目不能使用服务器控件的情况也来也多了,没有了服务器控件,前台以后台的数据交互,我觉得json 是不错的选择(特别是使用前框架,ajax请求返回json数据是相当有用的),以前是要用到json数据时就自己去拼数据,一直觉得麻烦,所以就有了这个类。主要也是看了一些网上的资料,和自己使用的心得写的。如果有更好的方法,或者是代码不好,错误度可以提示我,我会改过来。

           我知道.net 3.5 就自带json序列化了,一般都市用来序列化对象。我写的这个类也是有用到这个,因为反序列化简单。但是这个自带的,序列化出来的json格式不标准,有可能在前端用不了(php  json_decode 好像就不能用),所以最好就是要能够标准一些。下面是代码。

     1.这个是序列化的类,使用了自带序列化方法,所以要引入dll(System.ServiceModel.Web;System.Runtime.Serialization)

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Runtime.Serialization.Json;
      4 using System.Linq;
      5 using System.Web;
      6 using System.IO;
      7 using System.Data;
      8 using System.Text;
      9 using System.Reflection;
     10 
     11 namespace json
     12 {
     13     public class Jsonhelp
     14     {
     15       //对象级别的数据json化(最好在.net里使用(除非对象里头的属性都是string类型))
     16       public static string Objecttojson<T>(T t)
     17        {
     18            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
     19            MemoryStream ms = new MemoryStream();
     20            ser.WriteObject(ms, t);
     21            string sJson = Encoding.UTF8.GetString(ms.ToArray());
     22            ms.Close();
     23            return sJson;
     24        }
     25 
     26       //json 数据的反序列化(把json 数据转化为对象)
     27       public static T Jsontoobject<T>(string jsonString)
     28       {
     29           DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
     30           MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
     31           T obj = (T)ser.ReadObject(ms);
     32           return obj;
     33       }
     34 
     35     //针对前端识别不了有属性不是string的情况
     36       public static string ObjecttoSjson<T>(T t)
     37       {  
     38           StringBuilder sJson=new StringBuilder();
     39           Type type = t.GetType();
     40           sJson.Append("{");
     41         foreach (PropertyInfo pi in type.GetProperties())  
     42         {  
     43            object value = pi.GetValue(t, null); //用pi.GetValue获得值  
     44            string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作  
     45            sJson.Append('"');
     46            sJson.Append(name);
     47            sJson.Append('"');
     48            sJson.Append(':');
     49            sJson.Append('"');
     50            sJson.Append(value);
     51            sJson.Append('"');
     52            sJson.Append(',');
     53         }
     54         string strJson = string.Empty;
     55         if (sJson.ToString().Length > 1)
     56         {
     57             sJson.Remove(sJson.Length-1,1);
     58             sJson.Append("}");
     59             strJson = sJson.ToString();
     60         }
     61         else {
     62             strJson="";
     63         }
     64         return strJson;
     65       }
     66      //把datatable 数据序列化为json
     67      public static string Datatabletojson(DataTable dt)
     68      {
     69          StringBuilder sJson = new StringBuilder();
     70          if (dt.Rows.Count > 0) {
     71              sJson.Append("[");
     72              for (int i = 0; i < dt.Rows.Count; i++)
     73              {
     74                  sJson.Append('{');
     75                  for (int j = 0; j < dt.Columns.Count; j++)
     76                  {  
     77                      sJson.Append('"');
     78                      sJson.Append(dt.Columns[j].ColumnName);
     79                      sJson.Append('"');
     80                      sJson.Append(':');
     81                      sJson.Append('"');
     82                      sJson.Append(dt.Rows[i][j].ToString());
     83                      sJson.Append('"');
     84                    
     85                      if (j != dt.Columns.Count - 1)
     86                      {
     87                          sJson.Append(',');
     88                      }     
     89                  }
     90               sJson.Append('}');
     91               sJson.Append(',');
     92 
     93              }
     94          }
     95          sJson.Remove(sJson.Length - 1, 1);
     96          sJson.Append(']'); 
     97          return sJson.ToString();
     98      }
     99 
    100     //链式对象序列化成json
    101      public static string ListobjecttoSjson<T>(List<T> t)
    102      {
    103          StringBuilder sJson=new StringBuilder();
    104          if (t.Count > 0)
    105          {
    106              sJson.Append("[");
    107              foreach (T a in t)
    108              {
    109                  Type type = a.GetType();
    110                  StringBuilder strJson = new StringBuilder();
    111                  strJson.Append("{");
    112                  foreach (PropertyInfo pi in type.GetProperties())
    113                  {
    114                      object value = pi.GetValue(a, null); //用pi.GetValue获得值  
    115                      string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作  
    116                      strJson.Append('"');
    117                      strJson.Append(name);
    118                      strJson.Append('"');
    119                      strJson.Append(':');
    120                      strJson.Append('"');
    121                      strJson.Append(value);
    122                      strJson.Append('"');
    123                      strJson.Append(',');  
    124                  }
    125                  if (strJson.ToString().Length > 1)
    126                  {   strJson.Remove(strJson.Length - 1, 1);
    127                      strJson.Append("}");
    128                  }
    129                  sJson.Append(strJson.ToString());
    130                  sJson.Append(",");
    131              }
    132          }
    133          else {
    134              sJson.Append("");
    135          }
    136          if (sJson.ToString().Length > 1)
    137          {   sJson.Remove(sJson.Length - 1, 1);
    138              sJson.Append("]");
    139          }
    140          return sJson.ToString() ;
    141 
    142      }
    143    
    144 
    145 
    146 
    147     }
    148 }
    View Code

    2.这是使用的例子

     1  protected void Page_Load(object sender, EventArgs e)
     2         {
     3           
     4           //调用.net自带的类库序列化
     5           Person a = new Person();
     6           a.Age = 18;
     7           a.Name = "sb";
     8           string jsonString = Jsonhelp.Objecttojson<Person>(a);
     9           Response.Write(jsonString);
    10 
    11           //调用.net自带的类库序反列化
    12           Person b = new Person();
    13           b = Jsonhelp.Jsontoobject<Person>(jsonString);
    14           Response.Write(b.Name+"<br>");
    15 
    16           //对象序列化前端标准json数据格式
    17           Response.Write(Jsonhelp.ObjecttoSjson<Person>(b)+"<br>");
    18 
    19 
    20           //DataTable 序列化
    21           SqlConnection conn = new SqlConnection();
    22           conn = new SqlConnection();
    23           conn.ConnectionString = "Data Source=(local);Initial Catalog=KuaiPan;User ID=sa;Password=sb";
    24           conn.Open();
    25           string strsql = "select * from tb";
    26           SqlCommand cmd = new SqlCommand(strsql, conn);
    27           SqlDataReader sqlreader = cmd.ExecuteReader();
    28           DataTable dt = new DataTable();
    29           dt.Load(sqlreader);
    30           Response.Write(Jsonhelp.Datatabletojson(dt)+"<br><br><br>");
    31           
    32             
    33           //list对象集序列化 
    34           List<Person >t=new List<Person>();
    35           Person ds = new Person();
    36           ds.Age = 86;
    37           ds.Name = "屌丝";
    38           Person dd = new Person();
    39           dd.Age = 78;
    40           dd.Name = "你妹";
    41           t.Add(ds);
    42           t.Add(dd);
    43           Response.Write(Jsonhelp.ListobjecttoSjson(t));
    View Code

    3.这是结果

  • 相关阅读:
    Insertion Sort List
    Same Tree
    Binary Tree Level Order Traversal II
    Binary Tree Level Order Traversal
    ZigZag Conversion
    Reverse Integer
    String to Integer (atoi)
    Palindrome Number
    eclipse 导入tortoiseSVN检出项目,不显示svn信息(eclipse安装svn插件)
    exception ORA-00918: 未明确定义列
  • 原文地址:https://www.cnblogs.com/try-wyh/p/3447321.html
Copyright © 2011-2022 走看看