Json与实体类 转化

版权声明:本文为博主原创文章,若转载请标明。 https://blog.csdn.net/qq_36330228/article/details/89856511
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;
    }
}

没有更多推荐了,返回首页