123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- 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
- {
- /// <summary>
- /// Json工具类
- /// </summary>
- public static class JsonHelper
- {
- /// <summary>
- /// Json序列化
- /// </summary>
- public static string JsonSerializer<T>(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;
- }
- /// <summary>
- /// Json反序列化
- /// </summary>
- public static T JsonDeserialize<T>(string jsonString)
- {
- T obj = Activator.CreateInstance<T>();
- 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;
- }
- }
- }
|