1.先创建两个对象Directory和File
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JSONDemo
{
public class Directory
{
public string Name { get; set; }
public Directory Parent { get; set; }
public IList<File> Files { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JSONDemo
{
public class File
{
public string Name { get; set; }
public Directory Parent { get; set; }
}
}
2.序列化操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;
namespace JSONDemo
{
class Program
{
static void Main(string[] args)
{
Directory root = new Directory { Name = "GongHuiRoot" };
Directory documents = new Directory { Name = "GongHui's documents", Parent = root };
File file = new File { Name = "GongHuiJSONDemo.sln", Parent = documents };
documents.Files = new List<File> { file };
Console.WriteLine("----属性引用其本身对象的时,抛出异常----");
try
{
JsonConvert.SerializeObject(documents, Formatting.Indented);
}
catch (JsonSerializationException ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("----保存所有的引用类型----");
string all = JsonConvert.SerializeObject(documents, Formatting.Indented, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All
});
Console.WriteLine(all);
Console.WriteLine("--------保存引用类型对象----");
string obj = JsonConvert.SerializeObject(documents, Formatting.Indented, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
Console.WriteLine(obj);
}
}
}
3.运行后的结果
JSON源代码下载地址:http://download.csdn.net/detail/lovegonghui/9342751