JSON序列化与反序列化到文件

来源:互联网 发布:mlb淘宝代购是真的吗 编辑:程序博客网 时间:2024/05/16 10:07
一、序列化成一个文件

1.JSON序列化成一个文件,此文件到记事本可以打开。首先先创建一个Movie对象.

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace JSONDemo{    public class Movie    {        public string Name { get; set; }        public string Director { get; set; }        public int ReleaseYear { get; set; }    }}


2.实例化movie对象,并给对象属性赋值。并且序列化成一个文件。包含了两种方法。源代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using Newtonsoft.Json;namespace JSONDemo{    class Program    {        static void Main(string[] args)        {            Movie movie = new Movie             {                 Name="HAPPY FEET 2",                Director="Judy Morris,Warren Coleman,George Miller",                ReleaseYear=2006            };            //方法一:把序列化的JSON写入到一个文件中            System.IO.File.WriteAllText(@"D:\movie1.json", JsonConvert.SerializeObject(movie));            //方法二:直接序列化到文件中            using (System.IO.StreamWriter sw = System.IO.File.CreateText(@"D:\movie2.json"))            {                JsonSerializer serializer = new JsonSerializer();                serializer.Serialize(sw, movie);            }        }    }}


3.序列化的运行结果

 

 

 

 二、反序列化JSON文件

1.把JSON文件反序化成一个Movie对象。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using GongHuiNewtonsoft.Json;namespace JSONDemo{    class Program    {        static void Main(string[] args)        {            //方法一:反序列化JSON文件,并把文件内容写入到一个对象中.            Movie movie1 = JsonConvert.DeserializeObject<Movie>(System.IO.File.ReadAllText(@"D:\movie1.json"));            Console.WriteLine(movie1.Name);            Console.WriteLine(movie1.Director);                        Console.WriteLine(movie1.ReleaseYear);            //方法二:直接反序列化JSON文件,并把文件内容写入到一个对象中.            Movie movie2 = null;            using (System.IO.StreamReader sr = System.IO.File.OpenText(@"D:\movie2.json"))            {                JsonSerializer serializer = new JsonSerializer();                movie2 = serializer.Deserialize(sr, typeof(Movie)) as Movie;                            }            Console.WriteLine("==========================================");            Console.WriteLine(movie2.Name);            Console.WriteLine(movie2.Director);            Console.WriteLine(movie2.ReleaseYear);        }    }}


2.反序列化后运行的结果

 

JSON源代码下载地址:http://download.csdn.net/detail/lovegonghui/9342751


 

 

0 0
原创粉丝点击