用C#写一个JSon序列化和反序列化代码并附加案例
时间: 2023-07-18 10:31:43 浏览: 88
下面是使用 C# 对象进行 JSON 序列化和反序列化的示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Text.Json;
namespace JsonDemo
{
class Program
{
static void Main(string[] args)
{
// 对象序列化为 JSON 字符串
var person = new Person
{
Name = "John",
Age = 30,
IsStudent = true,
Hobbies = new List<string> { "reading", "traveling", "playing games" },
Address = new Address
{
Street = "123 Main St",
City = "New York",
State = "NY",
Zip = "10001"
}
};
var json = JsonSerializer.Serialize(person);
Console.WriteLine(json);
// JSON 字符串反序列化为对象
var jsonStr = "{\"name\":\"John\",\"age\":30,\"isStudent\":true,\"hobbies\":[\"reading\",\"traveling\",\"playing games\"],\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\",\"state\":\"NY\",\"zip\":\"10001\"}}";
var person2 = JsonSerializer.Deserialize<Person>(jsonStr);
Console.WriteLine(person2.Name);
Console.WriteLine(person2.Age);
Console.WriteLine(person2.IsStudent);
Console.WriteLine(string.Join(", ", person2.Hobbies));
Console.WriteLine(person2.Address.Street);
Console.WriteLine(person2.Address.City);
Console.WriteLine(person2.Address.State);
Console.WriteLine(person2.Address.Zip);
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public bool IsStudent { get; set; }
public List<string> Hobbies { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
}
```
以上代码中,我们定义了一个 `Person` 类和一个 `Address` 类,分别表示人和地址信息。使用 `System.Text.Json` 命名空间中的 `JsonSerializer` 类进行序列化和反序列化操作。在 `Main` 方法中,我们先创建一个 `Person` 对象,然后将其序列化为 JSON 字符串并输出。接着,我们将 JSON 字符串反序列化为 `Person` 对象,并输出其属性值。
输出结果如下:
```
{"Name":"John","Age":30,"IsStudent":true,"Hobbies":["reading","traveling","playing games"],"Address":{"Street":"123 Main St","City":"New York","State":"NY","Zip":"10001"}}
John
30
True
reading, traveling, playing games
123 Main St
New York
NY
10001
```
这个示例中,我们定义了一个 `Person` 对象,包含了名字、年龄、是否为学生、爱好和地址等信息。其中,爱好是一个字符串列表,地址是一个嵌套的对象。序列化后,得到的 JSON 字符串与前面所示的示例相同。反序列化后,我们可以得到与原对象相同的属性值。
阅读全文