C#自带的序列化、反序列化 /// <summary> /// 序列化 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static byte[] Serialize(object obj) { BinaryFormatter binaryF = new BinaryFormatter(); MemoryStream ms = new MemoryStream(1024 * 10); binaryF.Serialize(ms, obj); ms.Seek(0, SeekOrigin.Begin); byte[] buffer = new byte[(int)ms.Length]; ms.Read(buffer, 0, buffer.Length); ms.Close(); return buffer; } /// <summary> /// 反序列化 /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static object Deserialize(byte[] buffer) { BinaryFormatter binaryF = new BinaryFormatter(); MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length, false); object obj = binaryF.Deserialize(ms); ms.Close(); return obj; }
public class Datum { public string item { get; set; } public string quantity { get; set; } } public class RootObject { public string account { get; set; } public string password { get; set; } public List<Datum> data { get; set; } }List<RootObject> list = new List<RootObject>(); RootObject a = new RootObject(); a.account = "dl"; a.password = "123456"; Datum person = new Datum(); person.item = "111530504733"; person.quantity = "5"; list.Add(a);求代码,最后JSON出来的数据要这样的。{"account": "admin","password": "123456","data": [ {"item": "111530504733","quantity": "5"}, {"item": "111530504732","quantity": "5"}]} 或{"account": "admin","password": "123456","data": [ {"item": "111530504733","quantity": "5"}]}
我一般用json.net进行serialize和deserialize。
具体方法可以去查找一下材料就可以了,以前我做过类似的功能
/// <summary>
/// 序列化
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static byte[] Serialize(object obj)
{
BinaryFormatter binaryF = new BinaryFormatter();
MemoryStream ms = new MemoryStream(1024 * 10);
binaryF.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
byte[] buffer = new byte[(int)ms.Length];
ms.Read(buffer, 0, buffer.Length);
ms.Close(); return buffer;
} /// <summary>
/// 反序列化
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static object Deserialize(byte[] buffer)
{
BinaryFormatter binaryF = new BinaryFormatter();
MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length, false);
object obj = binaryF.Deserialize(ms);
ms.Close(); return obj;
}
{
public string item { get; set; }
public string quantity { get; set; }
} public class RootObject
{
public string account { get; set; }
public string password { get; set; }
public List<Datum> data { get; set; }
}List<RootObject> list = new List<RootObject>(); RootObject a = new RootObject();
a.account = "dl";
a.password = "123456"; Datum person = new Datum();
person.item = "111530504733";
person.quantity = "5";
list.Add(a);求代码,最后JSON出来的数据要这样的。{"account": "admin","password": "123456","data": [ {"item": "111530504733","quantity": "5"}, {"item": "111530504732","quantity": "5"}]}
或{"account": "admin","password": "123456","data": [ {"item": "111530504733","quantity": "5"}]}
或{"account": "admin","password": "123456","data": [ {"item": "111530504733","quantity": "5"}]}