C# json使用之Json.NET(6)——使用示例

以下为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<string> Roles { get; set; }
}

Account account = new Account
{
    Email = "james@example.com",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    Roles = new List<string> { "User", "Admin" }
};

//序列化对象,Formatting.Indented:进行格式化
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
// {
//   "Email": "james@example.com",
//   "Active": true,
//   "CreatedDate": "2013-01-20T00:00:00Z",
//   "Roles": [
//     "User",
//     "Admin"
//   ]
// }

Console.WriteLine(json);
    //反序列化
Account account = JsonConvert.DeserializeObject<Account>(json);

Console.WriteLine(account.Email);

从json文件中进行序列化和反序列化

序列化内容到文件中和从文件中进行反序列化,可以有效提高效率,减少内存的消耗。当有大量数据进行序列化和反序列化时,建议使用文件流进行操作。

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<Movie>(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));
}

JSON与原始内容序列化

此示例使用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 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<DataSet>(json);

DataTable dataTable = dataSet.Tables["Table1"];

Console.WriteLine(dataTable.Rows.Count);

foreach (DataRow row in dataTable.Rows)
{
    Console.WriteLine(row["id"] + " - " + row["item"]);
}

将JSON反序列化为匿名类型

此示例将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 

此示例创建一个继承自CustomCreationConverter <T>的类,该类实例化Person类型的Employee实例。

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<Person>
{
    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<Person>(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中的值填充现有对象实例。使用json对现有对象进行赋值。

public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public List<string> Roles { get; set; }
}

Account account = new Account
{
    Email = "james@example.com",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    Roles = new List<string>
    {
        "User",
        "Admin"
    }
};

string json = @"{
  'Active': false,
  'Roles': [
    'Expired'
  ]
}";

JsonConvert.PopulateObject(json, account);

Console.WriteLine(account.Email);
// james@example.com

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<Website>(json);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
    // Value cannot be null.
    // Parameter name: website
}

Website website = JsonConvert.DeserializeObject<Website>(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 = "joe@example.com",
    PasswordHash = "VHdlZXQgJ1F1aWNrc2lsdmVyJyB0byBASmFtZXNOSw=="
};

string json = JsonConvert.SerializeObject(account);

Console.WriteLine(json);
// {"FullName":"Joe User","EmailAddress":"joe@example.com"}

继承类DefaultContractResolver,进行有选择的忽略属性。

class LimitPropsContractResolver : DefaultContractResolver
{
string[] props = null;

bool retain;

/// <summary>
/// 构造函数
/// </summary>
/// <param name="props">传入的属性数组</param>
/// <param name="retain">true:表示props是需要保留的字段  false:表示props是要排除的字段</param>
public LimitPropsContractResolver(string[] props, bool retain = true)
{
//指定要序列化属性的清单
this.props = props;

this.retain = retain;
}

protected override IList<JsonProperty> CreateProperties(Type type,

MemberSerialization memberSerialization)
{
IList<JsonProperty> 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 = "joe@example.com",
    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"}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值