run in this way,   no why,   only for you heart
CSDN博客(点击进入) CSDN
51CTO(点击进入) 51CTO

Json与实体类 转化

public class JsonHelper
{
    ///Json To Object
    public static T JsonToObject<T>(string jsonText)
    {
        DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
        T obj = (T)s.ReadObject(ms);
        ms.Dispose();
        return obj;
    }

    ///Object To Json
    public static string ObjectToJSON<T>(T obj)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
        string result = string.Empty;
        using (MemoryStream ms = new MemoryStream())
        {
            serializer.WriteObject(ms, obj);
            ms.Position = 0;
            using (StreamReader read = new StreamReader(ms))
            {
                result = read.ReadToEnd();
            }
        }
        return result;
    }
}

posted @ 2019-05-05 22:11  _小龙人  阅读(69)  评论(0编辑  收藏  举报