In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to achieve JSON function and object serialization and deserialization in C #". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to implement JSON function and object serialization and deserialization in C #"!
References to Newtonsoft.Json packages
The json function is used in C # and requires the Newtonsoft.Json package, which can be installed by searching Newtonsoft.Json through the NuGet package Manager, or by using the following command under the NuGet package Manager console:
Install-package Newtonsoft.Json
Then reference the NewTonSoft.Json namespace. You can then convert the created object to a JSON string.
Serialize objects into JSON strings
Create a class as follows
Public class Student {public int Id {get; set;} public string Name {get; set;} public string Sex {get; set;} public string Description {get; set;}}
Generate an object and serialize it into a JSON string
List students = new List (); students.Add (new Student {Id = 1, Name = "Zhang San", Sex = "male", Description = "monitor"}); students.Add (new Student {Id = 2, Name = "Li Si", Sex = "female", Description = "group leader"}); students.Add (new Student {Id = 3, Name = "Wang Wu", Sex = "male", Description = "propaganda committee"}); string studentsJson = JsonConvert.SerializeObject (students); Console.WriteLine (studentsJson)
Output result:
[{"Id": 1, "Name": "Zhang San", "Sex": "male", "Description": "monitor"}, {"Id": 2, "Name": "Li Si", "Sex": "female", "Description": "group leader"}, {"Id": 3, "Name": "Wang Wu", "Sex": "male", "Description": "propaganda committee"}]
Ignore the serialization of fields using the [JsonIgnore] feature
Sometimes we may not want certain fields to participate in the JSON serialization of the object, so we can use the [JsonIgnore] property on this field. The object will not contain ignored fields after serialization.
Public class Student {public int Id {get; set;} public string Name {get; set;} [JsonIgnore] public string Sex {get; set;} public string Description {get; set;}}
Output result:
[{"Id": 1, "Name": "Zhang San", "Description": "monitor"}, {"Id": 2, "Name": "Li Si", "Description": "group leader"}, {"Id": 3, "Name": "Wang Wu", "Description": "propaganda committee"}]
Use the [JsonProperty] property to identify the serialized name of the field
Sometimes we may want to change the output name of the field when the object is serialized, for example, to simplify the field name to shorten the length of the JSON string, we can use the [JsonProperty] attribute to identify the field.
Public class Student {public int Id {get; set;} public string Name {get; set;} [JsonIgnore] public string Sex {get; set;} [JsonProperty ("Desc")] public string Description {get; set;}}
Output result:
[{"Id": 1, "Name": "Zhang San", "Desc": "monitor"}, {"Id": 2, "Name": "Li Si", "Desc": "group leader"}, {"Id": 3, "Name": "Wang Wu", "Desc": "propaganda committee"}]
Formatting output JSON string
If you want to output the generated JSON string in a friendly format, you can call the following method to convert
/ format JSON string / private static string ConvertJsonString (string str) {JsonSerializer serializer = new JsonSerializer (); TextReader tr = new StringReader (str); JsonTextReader jtr = new JsonTextReader (tr); object obj = serializer.Deserialize (jtr); if (obj! = null) {StringWriter textWriter = new StringWriter () JsonTextWriter jsonWriter = new JsonTextWriter (textWriter) {Formatting = Formatting.Indented, Indentation = 4, IndentChar =''}; serializer.Serialize (jsonWriter, obj); return textWriter.ToString ();} else {return str;}}
So the above JSON string can be output in formatted form instead.
List students = new List (); students.Add (new Student {Id = 1, Name = "Zhang San", Sex = "male", Description = "monitor"}); students.Add (new Student {Id = 2, Name = "Li Si", Sex = "female", Description = "group leader"}); students.Add (new Student {Id = 3, Name = "Wang Wu", Sex = "male", Description = "propaganda committee"}); / / string studentsJson = JsonConvert.SerializeObject (students) String studentsJson = ConvertJsonString (JsonConvert.SerializeObject (students)); Console.WriteLine (studentsJson)
Output result:
[
{
"Id": 1
"Name": "Zhang San"
"Desc": "monitor"
}
{
"Id": 2
"Name": "Li Si"
"Desc": "team leader"
}
{
"Id": 3
"Name": "Wang Wu"
"Desc": "publicity Committee"
}
]
Deserialization of JSON string
The following example deserializes the built JSON string into an object, and the class definition does not use the two additional features described above
Public class Student {public int Id {get; set;} public string Name {get; set;} / / [JsonIgnore] public string Sex {get; set;} / / [JsonProperty ("Desc")] public string Description {get; set }} string inputJsonString = @ "[{Id: 1, Name: 'Zhang San', Sex: 'male', Description: 'monitor'}, {Id: 2, Name:'Li Si', Sex: 'female', Description: 'group leader'}, {Id: 3, Name: 'Wang Wu', Sex: 'male', Description: 'propaganda Committee'}]; List objects = JsonConvert.DeserializeObject (inputJsonString) Foreach (Student item in objects) {Console.WriteLine ($"Id: {item.Id}, Name: {item.Name}, Sex: {item.Sex}, Description: {item.Description}");}
Output result:
Id: 1, Name: Zhang San, Sex: male, Description: monitor
Id: 2, Name: Li Si, Sex: female, Description: group leader
Id: 3, Name: Wang Wu, Sex: male, Description: publicity Committee
Serialization and deserialization of general objects
Sometimes we may need to serialize an object to a string, or deserialize a string to an object, such as encapsulating and transferring or storing a class. This first requires marking the object type as serializable using the feature [Serializable]
/ / tag type serializable [Serializable] public class Student {public int Id {get; set;} public string Name {get; set;} public string Sex {get; set;} public string Description {get; set;}}
Serialization and deserialization of general objects can be implemented in the following two ways
/ / serialize the object to the string / private static string Serialize (T obj) {try {IFormatter formatter = new BinaryFormatter (); MemoryStream stream = new MemoryStream (); formatter.Serialize (stream, obj); stream.Position = 0; byte [] buffer = new byte [stream.Length]; stream.Read (buffer, 0, buffer.Length) Stream.Flush (); stream.Close (); return Convert.ToBase64String (buffer);} catch (Exception ex) {throw new Exception (ex.Message);}} / deserialize the string to the object / public static T Deserialize (T obj, string str) {try {obj = default (T) IFormatter formatter = new BinaryFormatter (); byte [] buffer = Convert.FromBase64String (str); MemoryStream stream = new MemoryStream (buffer); obj = (T) formatter.Deserialize (stream); stream.Flush (); stream.Close ();} catch (Exception ex) {throw new Exception (ex.Message);} return obj;}
The following examples use the above two methods to serialize and deserialize generic objects
List students = new List (); students.Add (new Student {Id = 1, Name = "Zhang San", Sex = "male", Description = "monitor"}); students.Add (new Student {Id = 2, Name = "Li Si", Sex = "female", Description = "group leader"}); students.Add (new Student {Id = 3, Name = "Wang Wu", Sex = "male", Description = "propaganda committee"}); string studentsString = Serialize (students) Console.WriteLine ($"serialized object:\ n {studentsString}"); List objects = new List (); objects = Deserialize (objects, studentsString); Console.WriteLine ("deserialized object:"); foreach (Student item in objects) {Console.WriteLine ($"Id: {item.Id}, Name: {item.Name}, Sex: {item.Sex}");}
Output result:
Serialized object:
AAEAAAD/AQAAAAAAAAAMAgAAAEJDb25zb2xlQXBwMSwgVmVyc2lvbj0xLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPW51bGwEAQAAAHxTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW0NvbnNvbGVBcHAxLlN0dWRlbnQsIENvbnNvbGVBcHAxLCBWZXJzaW9uPTEuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbF1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24EAAAVQ29uc29sZUFwcDEuU3R1ZGVudFtdAgAAAAgICQMAAAADAAAAAwAAAAcDAAAAAAEAAAAEAAAABBNDb25zb2xlQXBwMS5TdHVkZW50AgAAAAkEAAAACQUAAAAJBgAAAAoFBAAAABNDb25zb2xlQXBwMS5TdHVkZW50BAAAABM8SWQ+a19fQmFja2luZ0ZpZWxkFTxOYW1lPmtfX0JhY2tpbmdGaWVsZBQ8U2V4PmtfX0JhY2tpbmdGaWVsZBw8RGVzY3JpcHRpb24+a19fQmFja2luZ0ZpZWxkAAEBAQgCAAAAAQAAAAYHAAAABuW8oOS4iQYIAAAAA+eUtwYJAAAABuePremVvwEFAAAABAAAAAIAAAAGCgAAAAbmnY7lm5sGCwAAAAPlpbMGDAAAAAnlsI/nu4Tplb8BBgAAAAQAAAADAAAABg0AAAAG546L5LqUCQgAAAAGDwAAAAzlrqPkvKDlp5TlkZgL
Deserialized object:
Id: 1, Name: Zhang San, Sex: male
Id: 2, Name: Li Si, Sex: female
Id: 3, Name: Wang Wu, Sex: male
At this point, I believe you have a deeper understanding of "how to achieve JSON functions and object serialization and deserialization in C #". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.