把Json实体类 转换成 Json字符串格式

//Model

//这里的json,可以多层嵌套

public class RootImages
    {
        public string pdfName { get; set; }
        public string company { get; set; }
        public string tpa { get; set; }
        public bool isRefresh { get; set; }
    }

#region 生成json
            string imagesJson = "";
            RootImages image = new RootImages();
            image.pdfName = pdfName;
            image.company = company;
            image.tpa = "shibo";
            image.isRefresh = isRefresh;
            imagesJson = ObjectToJSON<RootImages>(image);

 #endregion

       /// <summary>
        /// 把Json实体类 转换成 Json字符串格式
        /// </summary>
        /// <typeparam name="T">Json根节点类型</typeparam>
        /// <param name="obj">根节点对象</param>
        /// <returns></returns>
        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;
        }

猜你喜欢

转载自blog.csdn.net/Simon1003/article/details/81302543
今日推荐