Heim >Backend-Entwicklung >C#.Net-Tutorial >Objekt in JSON C# konvertieren
Der aktuelle Status des Objekts muss abgerufen werden, um es zu speichern oder später abzurufen. Dies sollte beim Codieren berücksichtigt werden. Es wird benutzerdefinierter Code hinzugefügt, um den Status des Objekts auszugeben. Dies wird in C# als Konvertieren des Objekts in einen Json-String bezeichnet. und die Codierung muss für jede einzelne Eigenschaft des Objekts erfolgen, abhängig von der Art des Wissens, das wir über die Art des Objekts haben. Der Code muss geändert werden, wenn sich die Definition des Objekttyps ändert, und wir verwenden die Json.NET-Bibliothek von Newtonsoft, um ein Objekt in C# in Json zu konvertieren, was uns mithilfe eines Codes eine vollständige Darstellung der Zeichenfolge unserer Objekte liefert in einer Zeile geschrieben.
Syntax:
Variable variable_name =Newtonsoft.Json.JsonConvert.SerializeObject(parameter);
Im Folgenden finden Sie die genannten Beispiele:
C#-Programm zur Demonstration der Konvertierung von Objekten in Json-Strings, was nichts anderes als die Serialisierung von Objekten in C# ist.
Code:
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); } } }
Ausgabe:
Erklärung:
C#-Programm zur Demonstration des Unterschieds zwischen manueller Serialisierung und Json-Serialisierung in einem Programm.
Code:
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;} } }
Ausgabe:
Erklärung:
Das obige ist der detaillierte Inhalt vonObjekt in JSON C# konvertieren. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!