.NET之JSON序列化运用

1.项目引用NuGet包;搜索:Newtonsoft.Json

2.序列号实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace JsonConvert
{
    class Program
    {
        static void Main(string[] args)
        {
            //js传递过程可直接将数据或者对象转成字符串进行传递
            string msg = "{*****}";//将对象字符串转成相应的对象
            //DeserializeObject<T> 是一个泛型。
            var model =  Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(msg);
            //将对象转成字符串
            DataTable dt = new DataTable();
            msg = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
        }
    }
}

3.常用api抛出数据实现类

 

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace JsonConvert
{
    public class ReturnResult<T>
    {
        public T data;
        public int status;
        public string Msg;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data">数据实体</param>
        /// <param name="stauts">1:成功,0:失败</param>
        public ReturnResult(T data, int stauts = 1,string msg="成功")
        {
            this.data = data;
            this.status = stauts;
            this.Msg = msg;
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <returns></returns>
        public string Serialize()
        {
            return JsonConvert.SerializeObject(this);
        }


    }
}

 

posted @ 2017-08-19 16:10  王彬-效率开发  阅读(260)  评论(0编辑  收藏  举报