0. 简介
JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
1. C#中使用JSON
1.1 环境配置
在NuGet包管理器中安装 System.Text.Json 即可。
1.2 序列化与反序列化
见第1节最后的代码。
1.3 写入文件与读入文件
见第1节最后的代码。
1.4 优美输出
见第1节最后的代码。
以下为示例代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
namespace ConsoleApp3 {
public class Student {
public string Name { get; set; }
public int Age { get; set; }
public string[] Hobbies { get; set; }
public IList<int> Scores { get; set; }
public IDictionary<string, int> Dict { get; set; }
}
class Program {
static void Main(string[] args) {
// 创建Student对象并赋值
Student stu = new Student();
stu.Name = "Duck Geng";
stu.Age = 22;
stu.Hobbies = new string[] { "吃饭", "睡觉" };
int[] scores = { 99, 100, 97 };
stu.Scores = new List<int>(scores);
stu.Dict = new Dictionary<string, int>();
stu.Dict["abc"] = 123;
stu.Dict["haha"] = 456;
// JSON序列化
string jsonStr = JsonSerializer.Serialize(stu);
Console.WriteLine(jsonStr);
// 将JSON字符串写入文件(显示指定UTF-8无BOM编码)
File.WriteAllText("out.txt", jsonStr, new UTF8Encoding(false));
// JSON反序列化
Student stu2 = JsonSerializer.Deserialize<Student>(jsonStr);
Console.WriteLine(stu2.Name);
Console.WriteLine(stu2.Scores.Count);
Console.WriteLine(stu2.Dict.Count);
// 从文件读取JSON字符串
string jsonStr2 = File.ReadAllText("out.txt", new UTF8Encoding(false));
Console.WriteLine(jsonStr2);
// 更优美地输出JSON字符串
JsonSerializerOptions options = new JsonSerializerOptions() { WriteIndented = true };
jsonStr = JsonSerializer.Serialize(stu, options);
Console.WriteLine(jsonStr);
}
}
}
运行结果:
2. JavaScript中使用JSON
2.1 序列化
见第2节最后的代码。
2.2 反序列化
见第2节最后的代码。
示例代码:
const student = {
"name": "耿鸭",
"age": 22,
"sex": true,
"hobbies": ["吃饭", "睡觉", "亲亲"],
};
// 序列化
const jsonStr = JSON.stringify(student);
console.log(jsonStr);
// 反序列化
const student2 = JSON.parse(jsonStr);
console.log(student2);
运行结果: