asp.net 下的 JSON 套件最佳利器「Newtonsoft.Json」

一、前言

筆者很常使用 Newtonsoft.JsonJSON 資料的序列化與反序列化,因為好用且有名因此介紹筆者常用的寫法給讀者。

二、開發環境

  • 整合開發環境:Visual Studio 2019
  • 語言:C#
  • .net framework:4.6.2

三、Newtonsoft.Json 的常用類別

  • JArray:代表 JSON array
  • JObject:代表 JSON 物件
  • JProperty:代表 JSON 屬性
  • JToken:代表 JSON Token,可為 JArray、JObject、JProperty、JValue …等
  • JValue:代表一個 JSON 值,可能是 string、integer、date …等

四、反序列化

圖、反序列化

  • 程式碼
var jsonStr = "{'a':'a1', 'b': 'b1'}";
return JsonConvert.DeserializeObject<JToken>(jsonStr);

圖、執行結果

五、序列化

圖、序列化

  • 程式碼
var jsonObj = new { a = "a1", b = "b1" };
return JsonConvert.SerializeObject(jsonObj);

圖、執行結果

六、參考

  1. Newtonsoft.Json

留言

這個網誌中的熱門文章

使用「Visual Studio 2019」建置 Windows 服務

使用「LINE Messaging API」發送 line 訊息

「Katalon Recorder」簡化測試腳本撰寫的工具

「Windows 認證管理員」修改 Bonobo Git Server 的 Git 帳號、密碼

使用「IMAP」讀取「Gmail」信件的主旨

「Windows PowerShell」介紹

在Visual Studio 2019 使用 Subversion 的客服端工具「AnkhSVN2019」

使用「Visual Studio 2019」進行網站負載測試

「OpenJDK」安裝步驟

使用「Visual Studio 2019」建置單元測試專案