一、JSON中使用C#File.WriteAllText与JObject.WriteTo方法写文件
1.两种方法写json文件,一种使用C#的File.WriteAllText(),另一种是JObject.WriteTo()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Linq;
namespace JSONDemo
{
class Program
{
static void Main(string[] args)
{
JObject o = new JObject(
new JProperty("Name","《华胥引》"),
new JProperty("Director","李达超"),
new JProperty("LaunchDate",DateTime.Now),
new JProperty("Summary","《华胥引》的故事是这样的:卫国公主以身殉国,不久死而复生,从此她改名换姓开始了新的旅程。电视剧改编自唐七公子的同名网络小说,于2015年七月首播,主演林源、郑嘉颖。不过和同类剧集相比,《华胥引》的人气就没那么高了。据网上的评论说,这部戏的主角和服装都不够抓眼。")
);
//方法一:
System.IO.File.WriteAllText(@"D:\movie.json1", o.ToString());
//方法二:
using (System.IO.StreamWriter file = System.IO.File.CreateText(@"D:\movie.json2"))
{
using (JsonTextWriter writer = new JsonTextWriter(file))
{
o.WriteTo(writer);
}
}
}
}
}
2.运行的结果
二、JSON中使用JsonTextReader,JObject,JToken读file
1.先使用C#中的File.OpenText()方法,然后使用JSON的相关类方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Linq;
namespace JSONDemo
{
class Program
{
static void Main(string[] args)
{
using (System.IO.StreamReader file = System.IO.File.OpenText(@"D:\Movie.json"))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o = (JObject)JToken.ReadFrom(reader);
Console.WriteLine(o["Name"]);
Console.WriteLine(o["Director"]);
Console.WriteLine(o["LaunchDate"]);
Console.WriteLine(o["Summary"]);
}
}
}
}
}
2.运行如下
JSON源代码下载地址:http://download.csdn.net/detail/lovegonghui/9342751