json.net java_C# 使用Json.NET对数据进行序列化和反序列化

c# json serialize and deserialize using json.net JsonConvert

Guide

Json.NET

JsonConvert.SerializeObject

JsonConvert.DeserializeObject

install

Use NuGet to download the package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

code

reference

using Newtonsoft.Json;

serialize collections

Product p1 = new Product

{

Name = "Product 1",

Price = 99.95m,

ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),

};

Product p2 = new Product

{

Name = "Product 2",

Price = 12.50m,

ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),

};

List products = new List();

products.Add(p1);

products.Add(p2);

string json = JsonConvert.SerializeObject(products, Formatting.Indented);

//[

// {

// "Name": "Product 1",

// "ExpiryDate": "2000-12-29T00:00:00Z",

// "Price": 99.95,

// "Sizes": null

// },

// {

// "Name": "Product 2",

// "ExpiryDate": "2009-07-31T00:00:00Z",

// "Price": 12.50,

// "Sizes": null

// }

//]

deserialize collections

string json = @"[

{

'Name': 'Product 1',

'ExpiryDate': '2000-12-29T00:00Z',

'Price': 99.95,

'Sizes': null

},

{

'Name': 'Product 2',

'ExpiryDate': '2009-07-31T00:00Z',

'Price': 12.50,

'Sizes': null

}

]";

List products = JsonConvert.DeserializeObject>(json);

Console.WriteLine(products.Count);

// 2

Product p1 = products[0];

Console.WriteLine(p1.Name);

// Product 1

serialize to json file

public class Movie

{

public string Name { get; set; }

public int Year { get; set; }

}

Movie movie = new Movie

{

Name = "Bad Boys",

Year = 1995

};

// serialize JSON to a string and then write string to a file

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);

}

Reference

History

20190910: created.

Copyright

Post author: kezunlin

Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值