using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace ToolsClassLibrary
{
///
/// Json工具类
///
public static class JsonHelper
{
///
/// Json序列化
///
public static string JsonSerializer(T obj)
{
string jsonString = string.Empty;
try
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
jsonString = Encoding.UTF8.GetString(ms.ToArray());
}
}
catch
{
jsonString = string.Empty;
}
return jsonString;
}
///
/// Json反序列化
///
public static T JsonDeserialize(string jsonString)
{
T obj = Activator.CreateInstance();
try
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());//typeof(T)
T jsonObject = (T)ser.ReadObject(ms);
ms.Close();
return jsonObject;
}
}
catch
{
return default(T);
}
}
public static byte[] SerializeBinary(object request)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
serializer.Serialize(memStream, request);
byte[] result=memStream.GetBuffer();
memStream.Close();
return result;
}
public static object DeSerializeBinary(byte[] buffer)
{
System.IO.MemoryStream memStream = new MemoryStream(buffer);
memStream.Position = 0;
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
object newobj = new double[2];
try
{
newobj = deserializer.Deserialize(memStream);
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
memStream.Close();
return newobj;
}
}
}