C# 使用 Newtonsoft.Json 序列化及反序列化
🏷️ C#
首先要添加对 Newtonsoft.Json.dll
的引用
下载地址:http://json.codeplex.com/
示例代码
csharp
using Newtonsoft.Json;
using System;
namespace NewtonsoftJsonSample
{
class Program
{
static void Main(string args)
{
string jsonUser = JsonConvert.SerializeObject(new User { Id = "user1", Name = "用户 1" });
Console.WriteLine(jsonUser);
User user = JsonConvert.DeserializeObject<User>(jsonUser);
Console.WriteLine(string.Format("Id:{0} Name:{1}", user.Id, user.Name));
Console.ReadLine();
}
class User
{
public string Id { get; set; }
public string Name { get; set; }
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
输出结果
js
{"Id":"user1","Name":"用户 1"}
Id:user1 Name:用户 1
1
2
2