C# .NET 3.5 对象序列化字符串
Posted jsper
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# .NET 3.5 对象序列化字符串相关的知识,希望对你有一定的参考价值。
支持任何形式的数据结构的对象
工具类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace Test class DataUtil /// <summary> /// 将对象序列化成字符串 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string SerializeToBase64<T>(T obj) try IFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, obj); stream.Position = 0; byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream.Flush(); stream.Close(); return Convert.ToBase64String(buffer); catch (Exception ex) throw new Exception("序列化失败,原因:" + ex.Message); /// <summary> /// 将字符串反序列化成对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="str"></param> /// <returns></returns> public static T DesrializeFromBase64<T>(T obj, string str) try obj = default(T); IFormatter formatter = new BinaryFormatter(); byte[] buffer = Convert.FromBase64String(str); MemoryStream stream = new MemoryStream(buffer); obj = (T)formatter.Deserialize(stream); stream.Flush(); stream.Close(); catch (Exception ex) throw new Exception("反序列化失败,原因:" + ex.Message); return obj;
示例:
Dictionary<string, object> parent = new Dictionary<string, object>(); parent["name"] = "张三"; parent["age"] = "35"; Dictionary<string, object> children = new Dictionary<string, object>(); children["name"] = "张三儿"; children["age"] = "7"; parent["children"] = children; // 对象序列化成字符串 string s = DataUtil.SerializeToBase64(parent); Console.WriteLine("序列化后结果: " + s); // 字符串反序列化成对象 Dictionary<string, object> d = new Dictionary<string, object>(); d = DataUtil.DesrializeFromBase64(d, s); Dictionary<string, object> cdr = (Dictionary<string, object>)d["children"]; object childName = cdr["name"]; Console.WriteLine("反序列化后取值: " + childName);
控制台打印结果:
序列化后结果: AAEAAAD/////AQAAAAAAAAAEAQAA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wODldLFtTeXN0ZW0uT2JqZWN0LCBtc2NvcmxpYiwgVmVyc2lvbj0yLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQHx/////P///wkFAAAABhEAAAAJ5byg5LiJ5YS/Ae7////8////CQgAAAAGFAAAAAE3Cw==
反序列化后取值: 张三儿
C# 使用Json.NET对数据进行序列化和反序列化 | c# json serialize and deserialize using json.net JsonConvert
本文首发于个人博客https://kezunlin.me/post/22391aa3/,欢迎阅读最新内容!
c# json serialize and deserialize using json.net JsonConvert
Guide
Json.NET
- JsonConvert.SerializeObject
- JsonConvert.DeserializeObject
install
Use NuGet to download the package
"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".
code
reference
using Newtonsoft.Json;
serialize collections
Product p1 = new Product
{
Name = "Product 1",
Price = 99.95m,
ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
};
Product p2 = new Product
{
Name = "Product 2",
Price = 12.50m,
ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
};
List<Product> products = new List<Product>();
products.Add(p1);
products.Add(p2);
string json = JsonConvert.SerializeObject(products, Formatting.Indented);
//[
// {
// "Name": "Product 1",
// "ExpiryDate": "2000-12-29T00:00:00Z",
// "Price": 99.95,
// "Sizes": null
// },
// {
// "Name": "Product 2",
// "ExpiryDate": "2009-07-31T00:00:00Z",
// "Price": 12.50,
// "Sizes": null
// }
//]
deserialize collections
string json = @"[
{
'Name': 'Product 1',
'ExpiryDate': '2000-12-29T00:00Z',
'Price': 99.95,
'Sizes': null
},
{
'Name': 'Product 2',
'ExpiryDate': '2009-07-31T00:00Z',
'Price': 12.50,
'Sizes': null
}
]";
List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
Console.WriteLine(products.Count);
// 2
Product p1 = products[0];
Console.WriteLine(p1.Name);
// Product 1
serialize to json file
public class Movie
{
public string Name { get; set; }
public int Year { get; set; }
}
Movie movie = new Movie
{
Name = "Bad Boys",
Year = 1995
};
// serialize JSON to a string and then write string to a file
File.WriteAllText(@"c:movie.json", JsonConvert.SerializeObject(movie));
// serialize JSON directly to a file
using (StreamWriter file = File.CreateText(@"c:movie.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, movie);
}
Reference
History
- 20190910: created.
Copyright
- Post author: kezunlin
- Post link: https://kezunlin.me/post/22391aa3/
- Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.
以上是关于C# .NET 3.5 对象序列化字符串的主要内容,如果未能解决你的问题,请参考以下文章
转载:在ASP.net 3.5中 用JSON序列化对象(两种方法)