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
- JSON序列化与反序列化到文件
- Json序列化 与反序列化
- JSON序列化与反序列化
- JSON序列化与反序列化
- Json序列化与反序列化
- Json序列化与反序列化
- JSON序列化与反序列化
- JSON序列化与反序列化
- JSON序列化与反序列化
- JSON序列化 与反序列化
- JSON序列化与反序列化
- JSON序列化与反序列化
- json 序列化与反序列化类
- C# Json 序列化与反序列化一
- C# Json 序列化与反序列化二
- JSON序列化与反序列
- POJO与JSON的序列化与反序列化
- 序列化与反序列化,及Json序列化反序列化
- 如何启动Nunit的调试功能
- RandomAccessFile 实现向文件中插入一段内容
- 页面之间的传值与接收以及解决中文乱码
- Linux init详解 (0,1,2,3,4,5,6)
- AppUtils 常用函数总结(Cocos2d-x 3.9)
- JSON序列化与反序列化到文件
- Spring+Hibernate整合框架下DAO的数据库访问方法
- DOM操作表格的各种属性[z]
- js 动态改变下拉菜单默认选中的值
- 实时数据库领域中有关数据压缩的认识误区
- 关于AppDelegate里面的那些函数方法
- Laravel 使用Redis 笔记
- Python下pickle加载文件问题
- 浅谈HTTP中Get与Post的区别