码迷,mamicode.com
首页 > Windows程序 > 详细

C# JSON字符串序列化与反序列化

时间:2016-05-13 12:56:18      阅读:404      评论:0      收藏:0      [点我收藏+]

标签:

C#将对象序列化成JSON字符串

public string GetJsonString()  
{  
    List<Product> products = new List<Product>(){  
    new Product(){Name="苹果",Price=5.5},  
    new Product(){Name="橘子",Price=2.5},  
    new Product(){Name="干柿子",Price=16.00}  
    };  
    ProductList productlist = new ProductList();  
    productlist.GetProducts = products;  
    return new JavaScriptSerializer().Serialize(productlist));  
}  
 
public class Product  
{  
    public string Name { get; set; }  
    public double Price { get; set; }  
}  
 
public class ProductList  
{  
    public List<Product> GetProducts { get; set; }  
} 

这里主要是使用JavaScriptSerializer来实现序列化操作,这样我们就可以把对象转换成Json格式的字符串,生成的结果如下:

{"GetProducts":[{"Name":"苹果","Price":5.5},{"Name":"橘子","Price":2.5},{"Name":"柿子","Price":16}]} 

如何将Json字符串转换成对象使用呢?

在实际开发中,经常有可能遇到用JS传递一个Json格式的字符串到后台使用,如果能自动将字符串转换成想要的对象,那进行遍历或其他操作时,就方便多了。那具体是如何实现的呢?

public static List<T> JSONStringToList<T>(this string JsonStr)  
{  
    JavaScriptSerializer Serializer = new JavaScriptSerializer();  
    List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);  
    return objs;  
}  
 
public static T Deserialize<T>(string json)  
{  
    T obj = Activator.CreateInstance<T>();  
    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))  
    {  
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());  
        return (T)serializer.ReadObject(ms);  
    }  
}  
 
string JsonStr = "[{Name:‘苹果‘,Price:5.5},{Name:‘橘子‘,Price:2.5},{Name:‘柿子‘,Price:16}]";  
List<Product> products = new List<Product>();  
products = JSONStringToList<Product>(JsonStr);  
 
foreach (var item in products)  
{  
    Response.Write(item.Name + ":" + item.Price + "<br />");  
}  
 
public class Product  
{  
    public string Name { get; set; }  
    public double Price { get; set; }  
} 

在上面的例子中,可以很方便的将Json字符串转换成List对象,操作的时候就方便多了~

 

------------------------------------------------------------------------------------------------------------

C#将对象序列化成JSON字符串  

using System.Web.Script;
using System.Web.Script.Serialization;


JavaScriptSerializer serializer = new JavaScriptSerializer();
      foreach (DataRow dr in dt.Rows)
      {
        Dictionary<string, string> data = new Dictionary<string, string>();
        data.Add("Dev_NO", dr["Dev_NO"].ToString());
        data.Add("Dev_Name", dr["Dev_Name"].ToString());
        data.Add("Ol_Phone", dr["Ol_Phone"].ToString());
        data.Add("Ol_IP", dr["Ol_IP"].ToString());
        data.Add("Ol_Status", dr["Ol_Status"].ToString());
        list.Add(data);
      }
      Response.Write(serializer.Serialize(list));

输出结果为:

[{"Dev_NO":"00066666","Dev_Name":"test","Ol_Phone":"13766668888","Ol_IP":"10.196.209.174","Ol_Status":"2"},{"Dev_NO":"000F0000","Dev_Name":"test_hzlkhq","Ol_Phone":"13066668888","Ol_IP":"192.168.1.198","Ol_Status":"2"}]

如何将Json字符串转换成对象使用呢?

public class Model
  {
    public string Dev_NO { get; set; }
    public string Dev_Name { get; set; }
    public string Ol_Phone { get; set; }
    public string Ol_IP { get; set; }
    public int Ol_Status { get; set; }
  }

  

string requestMes="[{\"Dev_NO\":\"00066666\",\"Dev_Name\":\"test\",\"Ol_Phone\":\"13766668888\",\"Ol_IP\":\"10.196.209.174\",\"Ol_Status\":\"2\"},{\"Dev_NO\":\"000F0000\",\"Dev_Name\":\"test_hzlkhq\",\"Ol_Phone\":\"13066668888\",\"Ol_IP\":\"192.168.1.198\",\"Ol_Status\":\"2\"}]";
JavaScriptSerializer serializer = new JavaScriptSerializer();
var Json = serializer.Deserialize<List<Model>>(requestMes);

第二种使用DataContractJsonSerializer,适用通用平台 

需要添加引用:System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:

using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;



//--------------------------
public class Model
  {
    public string Dev_NO { get; set; }
    public string Dev_Name { get; set; }
    public string Ol_Phone { get; set; }
    public string Ol_IP { get; set; }
    public int Ol_Status { get; set; }
  }

 

public class Test
  {
    public static DataTable getData()
    {
      var a = "{\"Dev_NO\":\"00066666\",\"Dev_Name\":\"test\",\"Ol_Phone\":\"13766668888\",\"Ol_IP\":\"10.196.209.174\",\"Ol_Status\":\"2\"}";
      var serializer = new DataContractJsonSerializer(typeof(List<DTUModel>));
      var mStream = new MemoryStream(Encoding.UTF8.GetBytes(a.ToString()));
      List<DTUModel> list = (List<DTUModel>)serializer.ReadObject(mStream);
      DataTable dt = new DataTable();
      return dt;
    }
  }

  

 

转: 善待自己,珍惜今天,恩泽他人,享受生活      C# JSON字符串序列化与反序列化(转)

转:http://blog.csdn.net/cjw13860421089/article/details/26374969

C# JSON字符串序列化与反序列化

标签:

原文地址:http://www.cnblogs.com/wangfuyou/p/5487495.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!