c#,Model 实体转json,字符串转json

本文介绍了两种将数据转换为JSON格式的方法:一种是将字符串直接转换为JSON,另一种是将.NET Model实体或集合转换为JSON。这两种方法都使用了JavaScriptSerializer进行序列化,并返回了包含JSON数据的HttpResponseMessage。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  public class JsonF
    {
        #region 字符串转json
        /// <summary>
        /// 字符串转json
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static HttpResponseMessage toJson(Object obj)
        {
            String str;
            if (obj is String || obj is Char)
            {
                str = obj.ToString();
            }
            else
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                str = serializer.Serialize(obj);
            }
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion

        #region Model 实体转json
        /// <summary>
        /// Model 实体转json
        /// </summary>
        /// <param name="Model">可以是单个实体,也可是实体集(即:ToList())</param>
        /// <returns></returns>
        public static HttpResponseMessage PostModel(object Model)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string str = serializer.Serialize(Model);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion
    }

 

转载于:https://www.cnblogs.com/SeNaiTes/p/9006672.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值