以下为json.net的使用示例程序代码,序列化和反序列化json。摘自官方使用示例。
进行C#对象的序列化和反序列化,对象可以是类、数组、集合、列表等等,列表在json中序列化后为数组形式。序列化时,还可以决定是否进行输出的json格式化,使用Formatting.Indented
参数。
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList Roles { get; set; }
}
Account account = new Account
{
Email = "[email protected]",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List { "User", "Admin" }
};
//序列化对象,Formatting.Indented:进行格式化
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
// {
// "Email": "[email protected]",
// "Active": true,
// "CreatedDate": "2013-01-20T00:00:00Z",
// "Roles": [
// "User",
// "Admin"
// ]
// }
Console.WriteLine(json);
//反序列化
Account account = JsonConvert.DeserializeObject(json);
Console.WriteLine(account.Email);
序列化内容到文件中和从文件中进行反序列化,可以有效提高效率,减少内存的消耗。当有大量数据进行序列化和反序列化时,建议使用文件流进行操作。
public class Movie
{
public string Name { get; set; }
public int Year { get; set; }
}
Movie movie = new Movie
{
Name = "Bad Boys",
Year = 1995
};
// 序列化json,并写入到文件中
File.WriteAllText(@"c:\movie.json", JsonConvert.SerializeObject(movie));
// serialize JSON directly to a file
using (StreamWriter file = File.CreateText(@"c:\movie.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, movie);
}
// 从文件中反序列化json
Movie movie1 = JsonConvert.DeserializeObject(File.ReadAllText(@"c:\movie.json"));
// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\movie.json"))
{
JsonSerializer serializer = new JsonSerializer();
Movie movie2 = (Movie)serializer.Deserialize(file, typeof(Movie));
}
此示例使用JRaw属性将JSON与原始内容序列化。
public class JavaScriptSettings
{
public JRaw OnLoadFunction { get; set; }
public JRaw OnUnloadFunction { get; set; }
}
JavaScriptSettings settings = new JavaScriptSettings
{
OnLoadFunction = new JRaw("OnLoad"),
OnUnloadFunction = new JRaw("function(e) { alert(e); }")
};
string json = JsonConvert.SerializeObject(settings, Formatting.Indented);
Console.WriteLine(json);
// {
// "OnLoadFunction": OnLoad,
// "OnUnloadFunction": function(e) { alert(e); }
// }
DataSet dataSet = new DataSet("dataSet");
dataSet.Namespace = "NetFrameWork";
DataTable table = new DataTable();
DataColumn idColumn = new DataColumn("id", typeof(int));
idColumn.AutoIncrement = true;
DataColumn itemColumn = new DataColumn("item");
table.Columns.Add(idColumn);
table.Columns.Add(itemColumn);
dataSet.Tables.Add(table);
for (int i = 0; i < 2; i++)
{
DataRow newRow = table.NewRow();
newRow["item"] = "item " + i;
table.Rows.Add(newRow);
}
dataSet.AcceptChanges();
string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
Console.WriteLine(json);
// {
// "Table1": [
// {
// "id": 0,
// "item": "item 0"
// },
// {
// "id": 1,
// "item": "item 1"
// }
// ]
// }
DataSet dataSet = JsonConvert.DeserializeObject(json);
DataTable dataTable = dataSet.Tables["Table1"];
Console.WriteLine(dataTable.Rows.Count);
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["id"] + " - " + row["item"]);
}
此示例将JSON反序列化为匿名类型。
var definition = new { Name = "" };
string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
Console.WriteLine(customer1.Name);
// James
string json2 = @"{'Name':'Mike'}";
var customer2 = JsonConvert.DeserializeAnonymousType(json2, definition);
Console.WriteLine(customer2.Name);
// Mike
此示例创建一个继承自CustomCreationConverter
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
}
public class Employee : Person
{
public string Department { get; set; }
public string JobTitle { get; set; }
}
public class PersonConverter : CustomCreationConverter
{
public override Person Create(Type objectType)
{
return new Employee();
}
}
string json = @"{
'Department': 'Furniture',
'JobTitle': 'Carpenter',
'FirstName': 'John',
'LastName': 'Joinery',
'BirthDate': '1983-02-02T00:00:00'
}";
Person person = JsonConvert.DeserializeObject(json, new PersonConverter());
Console.WriteLine(person.GetType().Name);
// Employee
Employee employee = (Employee)person;
Console.WriteLine(employee.JobTitle);
// Carpenter
此示例使用条件属性从序列化中排除属性。当进行序列化时需要忽略排除某个属性,可以进行以下操作。
public class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
public bool ShouldSerializeManager()
{
// don't serialize the Manager property if an employee is their own manager
return (Manager != this);
}
}
Employee joe = new Employee();
joe.Name = "Joe Employee";
Employee mike = new Employee();
mike.Name = "Mike Manager";
joe.Manager = mike;
// mike is his own manager
// ShouldSerialize will skip this property
mike.Manager = mike;
string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
Console.WriteLine(json);
// [
// {
// "Name": "Joe Employee",
// "Manager": {
// "Name": "Mike Manager"
// }
// },
// {
// "Name": "Mike Manager"
// }
// ]
此示例使用JSON中的值填充现有对象实例。使用json对现有对象进行赋值。
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public List Roles { get; set; }
}
Account account = new Account
{
Email = "[email protected]",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List
{
"User",
"Admin"
}
};
string json = @"{
'Active': false,
'Roles': [
'Expired'
]
}";
JsonConvert.PopulateObject(json, account);
Console.WriteLine(account.Email);
// [email protected]
Console.WriteLine(account.Active);
// false
Console.WriteLine(string.Join(", ", account.Roles.ToArray()));
// User, Admin, Expired
此示例使用ConstructorHandling设置使用其非公共构造函数成功反序列化类。
public class Website
{
public string Url { get; set; }
private Website()
{
}
public Website(Website website)
{
if (website == null)
{
throw new ArgumentNullException(nameof(website));
}
Url = website.Url;
}
}
string json = @"{'Url':'http://www.google.com'}";
try
{
JsonConvert.DeserializeObject(json);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
// Value cannot be null.
// Parameter name: website
}
Website website = JsonConvert.DeserializeObject(json, new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
});
Console.WriteLine(website.Url);
// http://www.google.com
序列化时可以选择忽略某些属性。
public class Account
{
public string FullName { get; set; }
public string EmailAddress { get; set; }
[JsonIgnore]
public string PasswordHash { get; set; }
}
Account account = new Account
{
FullName = "Joe User",
EmailAddress = "[email protected]",
PasswordHash = "VHdlZXQgJ1F1aWNrc2lsdmVyJyB0byBASmFtZXNOSw=="
};
string json = JsonConvert.SerializeObject(account);
Console.WriteLine(json);
// {"FullName":"Joe User","EmailAddress":"[email protected]"}
DefaultContractResolver
,进行有选择的忽略属性。class LimitPropsContractResolver : DefaultContractResolver
{
string[] props = null;
bool retain;
///
/// 构造函数
///
/// 传入的属性数组
/// true:表示props是需要保留的字段 false:表示props是要排除的字段
public LimitPropsContractResolver(string[] props, bool retain = true)
{
//指定要序列化属性的清单
this.props = props;
this.retain = retain;
}
protected override IList CreateProperties(Type type,
MemberSerialization memberSerialization)
{
IList list =
base.CreateProperties(type, memberSerialization);
//只保留清单有列出的属性
return list.Where(p => {
if (retain)
{
return props.Contains(p.PropertyName);
}
else
{
return !props.Contains(p.PropertyName);
}
}).ToList();
}
}
public class Account
{
public string FullName { get; set; }
public string EmailAddress { get; set; }
public string PasswordHash { get; set; }
}
Account account = new Account
{
FullName = "Joe User",
EmailAddress = "[email protected]",
PasswordHash = "VHdlZXQgJ1F1aWNrc2lsdmVyJyB0byBASmFtZXNOSw=="
};
JsonSerializerSettings jsetting = new JsonSerializerSettings();
jsetting.ContractResolver = new LimitPropsContractResolver(new string[]{"EmailAddress","PasswordHash"});
string Json = JsonConvert.SerializeObject(account, Formatting.None, jsetting);
// {"FullName":"Joe User"}