您的位置:首页 > Web前端 > JavaScript

JSON使用TypeNameHandling序列化与反序列化.NET类型和声明类型

2015-12-11 13:27 711 查看
1.先创建一个抽象类WildAnimal,再创建一个派生类Panda,最后创建一个含有抽象类集合的PandaInfo类.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JSONDemo
{
public abstract class WildAnimal
{
public string Name { get; set; }
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JSONDemo
{
public class Panda : WildAnimal
{
public string Food { get; set; }
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JSONDemo
{
public class PandaInfo
{
public int Lifetime { get; set; }
public IList<WildAnimal> WildAnimal { 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)
{
PandaInfo info = new PandaInfo()
{
Lifetime = 25,
WildAnimal = new List<WildAnimal>
{
new Panda
{
Name="Meimei",
Food="bamboo"
}
}
};

Console.WriteLine("----------序列化包含声明类型与.NET类型------------");
string all = JsonConvert.SerializeObject(info, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});
Console.WriteLine(all);

Console.WriteLine("--------------序列化包含.NET类型------------------");
string auto = JsonConvert.SerializeObject(info, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto
});
Console.WriteLine(auto);

Console.WriteLine("--------------反序列化包含.NET类型----------------");
PandaInfo info2 = JsonConvert.DeserializeObject<PandaInfo>(auto, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto
});
Console.WriteLine(info2.Lifetime);
Panda p = info2.WildAnimal[0] as Panda;
Console.WriteLine(p.Food);
Console.WriteLine(p.Name);
}
}
}


3.运行的结果



JSON源代码下载地址:http://download.csdn.net/detail/lovegonghui/9342751
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: