类转Json

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Runtime.Serialization.Json;

namespace WebApplication1.Common
{
    public class Method
    {
        public static string ObjectToJson(object obj)
        {
            if (obj == null) return string.Empty;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            serializer.WriteObject(stream, obj);
            byte[] dataBytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(dataBytes, 0, (int)stream.Length);
            return Encoding.UTF8.GetString(dataBytes);
        }
    }
}

 

posted @ 2018-10-25 14:06  江境纣州  阅读(11)  评论(0编辑  收藏  举报