必須取得物件的當前狀態來儲存它或稍後檢索它,編碼時應考慮這一點,添加自訂程式碼來輸出物件的狀態,這在C#中稱為將物件轉換為Json字串必鬚根據我們對物件類型的了解類型,對物件的每個屬性進行編碼。當物件類型的定義發生變化時,必須更改程式碼,並且我們使用 Newtonsoft 的 Json.NET 程式庫將物件轉換為 C# 中的 Json,它使用程式碼為我們提供了物件字串的完整表示用單行寫的。
文法:
Variable variable_name =Newtonsoft.Json.JsonConvert.SerializeObject(parameter);
C# 中物件到 JSON 字串的轉換
- 讓我們看看如何使用 NewtonsoftJson 完成物件的序列化,只不過是在 C# 中將物件轉換為 Json 字串。
- 建立一個新的 Visual Studio 項目,作為將物件轉換為 Json 字串的第一步。
- NewtonsoftJson 使用 Nuget 安裝。
- 建立一個範例類別來序列化,只不過將物件轉換為 Json 字串。
- 然後建立方法將物件轉換為 Json 字串或在 C# 中序列化物件。
- 最後執行程式將C#中的物件序列化,無非就是將C#中的物件轉換為Json字串。
將物件轉換為 JSON C# 的範例
下面給出的是提到的例子:
範例#1
C# 程序,示範物件到 Json 字串的轉換,這只不過是 C# 中物件的序列化。
代碼:
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; //a namespace called Serial is defined namespace Serial { //a class called Data is defined public class Data { //a string variable is defined which can be set or retrieved using get or set method public string Name1 { get; set; } //a list is defined which can be set or retrieved using get or set method public List<int> Ids { get; set; } //a method called Print is defined in which the name and the list is printed public void Print() { Console.WriteLine("The Name is: " + Name1); Console.WriteLine("The Identifiers used are: " + string.Join<int>(",", Ids)); Console.WriteLine(); Console.WriteLine(); } } //a class called check is defined public class Check { //a file path is defined and stored in a string variable const string fPath = @"d:\ex.txt"; //Serialize method is defined in which instances of Json writer and Stream writer classes are defined to write into the file public static void Serialize(object ob) { varserialise = new JsonSerializer(); using (var ns = new StreamWriter(fPath)) using (JsonWriter writer1 = new JsonTextWriter(ns)) { serialise.Serialize(writer1, ob); } } //Deserialize method is defined in which instances of Json text reader and Stream reader classes are defined to read from the file public static object Deserialize(string pa) { varserialise = new JsonSerializer(); using (var ns = new StreamReader(pa)) using (var reader1 = new JsonTextReader(ns)) { return serialise.Deserialize(reader1); } } //main method is called public static void Main(string[] args) { vardat = new Data { Name1 = "ShobhaShivakumar", Ids = new List<int>{ 10, 20, 30, 40 } }; Console.WriteLine("Before serialization of the objects, the list of the objects are:"); Console.WriteLine("-------------------------------------------------------------------"); Console.WriteLine(); dat.Print(); Serialize(dat); vardeserialise = Deserialize(fPath); Console.WriteLine("After de-serialization of the object, the objects are:"); Console.WriteLine("---------------------------"); Console.WriteLine(); Console.WriteLine(deserialise); } } }</int></int></int>
輸出:
說明:
- 在上面的程式中,定義了一個名為 Serial 的命名空間。然後定義一個名為Data的類別。然後定義一個字串變量,可以使用 get 或 set 方法來設定或檢索該變數。然後定義一個列表,可以使用 get 或 set 方法設定或檢索該列表。然後定義一個名為 Print 的方法,在其中列印名稱和清單。然後定義一個名為check的類別。然後定義檔案路徑並將其儲存在字串變數中。
- 然後定義了 Serialize 方法,其中定義了 Jsonwriter 和 Streamwriter 類別的實例來寫入檔案。然後定義 De serialize 方法,其中定義 Jsontext reader 和 Streamreader 類別的實例來從檔案中讀取。然後呼叫 main 方法,該方法呼叫該方法來顯示物件序列化之前的輸出。
範例#2
C# 程式來示範程式中手動序列化和 Json 序列化的差異。
代碼:
using System; using System.Text; using System.Collections.Generic; //a class called check is defined public class Check { //main method is called public static void Main() { //an instance of the Create request1 class and string builder class is created var request = CreateRequest1(); var output1 = new StringBuilder(); //Since we are using manual serialization here, we have to output the properties manually output1.AppendFormat("The unique ID is: {0}\n", request.UniqueID); output1.AppendFormat("The unique Name is: {0}\n", request.UniqueName); output1.AppendFormat("The unique Surname is: {0}\n", request.UniqueSurname); output1.AppendFormat("The Last Sign In is: {0}\n", request.UniqueLastSignIn); //We need to make use of for loop to output the nested attributes in case of manual serialization output1.AppendFormat("The Attributes are:\n"); foreach (varsh in request.UniqueAttributes) { output1.AppendFormat(" {0}\n", sh); } Console.WriteLine(output1.ToString()); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(request); //We are using Json serialization to improve the readability Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(request, Newtonsoft.Json.Formatting.Indented)); } //a method called Create request1 is defined public static Req CreateRequest1() { return new Req { UniqueID = 10, UniqueName = "Shobha", UniqueSurname = "Shivakumar", UniqueLastSignIn = DateTime.Now, UniqueAttributes = new List<string> { "Beautiful", "Tall", "Intelligent", "Wise", } }; } //a class called req is created public class Req { public intUniqueID {get;set;} public string UniqueName {get;set;} public string UniqueSurname {get;set;} public DateTimeUniqueLastSignIn {get;set;} public List<string>UniqueAttributes {get;set;} } }</string></string>
輸出:
說明:
- 在上面的程式中,定義了一個名為check的類別。然後呼叫main方法。然後建立 Create request1 類別和字串產生器類別的實例。然後,由於我們在這裡使用手動序列化,因此我們必須手動輸出屬性。然後我們需要利用for迴圈來輸出嵌套的屬性,因為這是手動序列化的情況。
- 然後我們使用Json序列化來提高可讀性。然後定義了一個名為 Create request1 的方法。然後建立一個名為 req 的類,其中使用 get 或 set 方法來設定和檢索所有屬性。
以上是將物件轉換為 JSON C#的詳細內容。更多資訊請關注PHP中文網其他相關文章!

C#和.NET的關係是密不可分的,但它們不是一回事。 C#是一門編程語言,而.NET是一個開發平台。 C#用於編寫代碼,編譯成.NET的中間語言(IL),由.NET運行時(CLR)執行。

C#.NET依然重要,因為它提供了強大的工具和庫,支持多種應用開發。 1)C#結合.NET框架,使開發高效便捷。 2)C#的類型安全和垃圾回收機制增強了其優勢。 3).NET提供跨平台運行環境和豐富的API,提升了開發靈活性。

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C#和.NET通過不斷的更新和優化,適應了新興技術的需求。 1)C#9.0和.NET5引入了記錄類型和性能優化。 2).NETCore增強了雲原生和容器化支持。 3)ASP.NETCore與現代Web技術集成。 4)ML.NET支持機器學習和人工智能。 5)異步編程和最佳實踐提升了性能。

c#.netissutableforenterprise-levelapplications withemofrosoftecosystemdueToItsStrongTyping,richlibraries,androbustperraries,androbustperformance.however,itmaynotbeidealfoross-platement forment forment forment forvepentment offependment dovelopment toveloperment toveloperment whenrawspeedsportor whenrawspeedseedpolitical politionalitable,

C#在.NET中的編程過程包括以下步驟:1)編寫C#代碼,2)編譯為中間語言(IL),3)由.NET運行時(CLR)執行。 C#在.NET中的優勢在於其現代化語法、強大的類型系統和與.NET框架的緊密集成,適用於從桌面應用到Web服務的各種開發場景。

C#是一種現代、面向對象的編程語言,由微軟開發並作為.NET框架的一部分。 1.C#支持面向對象編程(OOP),包括封裝、繼承和多態。 2.C#中的異步編程通過async和await關鍵字實現,提高應用的響應性。 3.使用LINQ可以簡潔地處理數據集合。 4.常見錯誤包括空引用異常和索引超出範圍異常,調試技巧包括使用調試器和異常處理。 5.性能優化包括使用StringBuilder和避免不必要的裝箱和拆箱。

C#.NET應用的測試策略包括單元測試、集成測試和端到端測試。 1.單元測試確保代碼的最小單元獨立工作,使用MSTest、NUnit或xUnit框架。 2.集成測試驗證多個單元組合的功能,常用模擬數據和外部服務。 3.端到端測試模擬用戶完整操作流程,通常使用Selenium進行自動化測試。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

記事本++7.3.1
好用且免費的程式碼編輯器

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SublimeText3漢化版
中文版,非常好用

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器