【转载】C#使用Newtonsoft.Json组件来序列化对象

在Asp.Net网站开发的过程中,很多时候会遇到对象的序列化和反序列化操作,Newtonsoft.Json组件是专门用来序列化和反序列化操作的一个功能组件,引入这个DLL组件后,就可使用JsonConvert.SerializeObject方法来序列化C#的对象。JsonConvert.SerializeObject方法的签名为JsonConvert.SerializeObject(object value),value代表具体需要序列化的对象,当然JsonConvert.SerializeObject方法还有几个重载方法。

(1)首先在项目中引入Newtonsoft.Json.Dll项目组件

(2)在命名空间处引入组件:using Newtonsoft.Json;

(3)在具体需要C#对象序列化的地方调用序列化函数JsonConvert.SerializeObject方法。具体例子如下:

  

 List<TestModel> testList = new List<ConsoleApplication1.TestModel>();

            testList.Add(new TestModel()
            {
                 Index=1,
                 Name="Index1"
            });
            testList.Add(new TestModel()
            {
                Index = 2,
                Name = "Index2"
            });
            testList.Add(new TestModel()
            {
                Index = 2,
                Name = "Index2"
            });

          var jsonStr=  Newtonsoft.Json.JsonConvert.SerializeObject(testList);

 

posted @ 2019-06-23 16:02  江湖逍遥  阅读(2853)  评论(0编辑  收藏  举报