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);
運行結果: