1. Installation
First, the library needs to be installed through NuGet. It can be installed through the following command:
Install-Package
2. Basic serialization and deserialization
Serialization (convert object to JSON string)
using ; using System; public class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { // Create a Person object Person person = new Person { Name = "John", Age = 30 }; //Usage method to serialize object into JSON string string json = (person); // Output JSON string (json); // Output: {"Name":"John","Age":30} } }
Deserialization (convert JSON string to object)
using ; using System; public class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { // JSON string string json = "{\"Name\":\"John\",\"Age\":30}"; //Usage method deserializes JSON string into Person object Person person = <Person>(json); // Output object properties ($"Name: {}, Age: {}"); // Output: Name: John, Age: 30 } }
3. Format JSON output
AvailableTo format JSON output to make it easier to read.
using ; using System; public class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { // Create a Person object Person person = new Person { Name = "John", Age = 30 }; // Use method to serialize the object into a JSON string and format the output string json = (person, ); // Output formatted JSON string (json); // Output: // { // "Name": "John", // "Age": 30 // } } }
4. Handle JSON attribute names
Available[JsonProperty]
The attribute to specify the JSON attribute name is different from the C# attribute name.
using ; using System; public class Person { [JsonProperty("full_name")] public string Name { get; set; } [JsonProperty("years_old")] public int Age { get; set; } } class Program { static void Main() { // Create a Person object Person person = new Person { Name = "John", Age = 30 }; // Serialize objects string json = (person); // Output JSON string (json); // Output: {"full_name":"John","years_old":30} // Deserialize JSON strings Person deserializedPerson = <Person>(json); // Output object properties ($"Name: {}, Age: {}"); // Output: Name: John, Age: 30 } }
5. Ignore attributes
Available[JsonIgnore]
Attributes to ignore an attribute so that it does not participate in serialization and deserialization.
using ; using System; public class Person { public string Name { get; set; } [JsonIgnore] public int Age { get; set; } } class Program { static void Main() { // Create a Person object Person person = new Person { Name = "John", Age = 30 }; // Serialize objects string json = (person); // Output JSON string (json); // Output: {"Name":"John"} // Deserialize JSON strings Person deserializedPerson = <Person>(json); // Output object properties ($"Name: {}, Age: {}"); // Output: Name: John, Age: 0 (Age is ignored, the default value is 0) } }
6. Process empty values
AvailableNullValueHandling
To control how to handle null values during serialization.
using ; using System; public class Person { public string Name { get; set; } public int? Age { get; set; } // Use nullable type} class Program { static void Main() { // Create a Person object with Age null Person person = new Person { Name = "John", Age = null }; // Serialize the object, ignore empty values var settings = new JsonSerializerSettings { NullValueHandling = }; string json = (person, settings); // Output JSON string (json); // Output: {"Name":"John"} // Deserialize JSON strings Person deserializedPerson = <Person>(json); // Output object properties ($"Name: {}, Age: {}"); // Output: Name: John, Age: (Age is null) } }
7. Custom serialization and deserialization
Can be achieved byJsonConverter
Customize serialization and deserialization logic.
using ; using System; public class Person { public string Name { get; set; } public int Age { get; set; } } public class PersonConverter : JsonConverter<Person> { public override void WriteJson(JsonWriter writer, Person value, JsonSerializer serializer) { (); ("full_name"); (); ("years_old"); (); (); } public override Person ReadJson(JsonReader reader, Type objectType, Person existingValue, bool hasExistingValue, JsonSerializer serializer) { var jsonObject = (reader); return new Person { Name = (string)jsonObject["full_name"], Age = (int)jsonObject["years_old"] }; } } class Program { static void Main() { // Create a Person object Person person = new Person { Name = "John", Age = 30 }; // Serialize with custom PersonConverter string json = (person, new PersonConverter()); // Output JSON string (json); // Output: {"full_name":"John","years_old":30} // Deserialize with custom PersonConverter Person deserializedPerson = <Person>(json, new PersonConverter()); // Output object properties ($"Name: {}, Age: {}"); // Output: Name: John, Age: 30 } }
8. Process date format
AvailableDateFormatString
To specify the serialization format of the date.
using ; using System; public class Event { public string Name { get; set; } public DateTime Date { get; set; } } class Program { static void Main() { // Create an Event object Event event = new Event { Name = "Conference", Date = new DateTime(2023, 10, 15) }; // Use DateFormatString to specify date format var settings = new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd" }; string json = (event, settings); // Output JSON string (json); // Output: {"Name":"Conference","Date":"2023-10-15"} // Deserialize JSON strings Event deserializedEvent = <Event>(json, settings); // Output object properties ($"Name: {}, Date: {}"); // Output: Name: Conference, Date: 10/15/2023 12:00:00 AM } }
9. Handle circular references
When there are circular references between objects, you can useReferenceLoopHandling
To deal with it.
using ; using System; public class Employee { public string Name { get; set; } public Employee Manager { get; set; } } class Program { static void Main() { // Create two Employee objects and form a circular reference Employee employee1 = new Employee { Name = "John" }; Employee employee2 = new Employee { Name = "Jane", Manager = employee1 }; = employee2; // Use to handle circular references var settings = new JsonSerializerSettings { ReferenceLoopHandling = }; string json = (employee1, settings); // Output JSON string (json); // Output: {"Name":"John","Manager":{"Name":"Jane"}} } }
10. Using LINQ to JSON
The LINQ to JSON function is also provided, allowing the use of LINQ to query JSON data.
using ; using System; class Program { static void Main() { // JSON string string json = "{\"Name\":\"John\",\"Age\":30,\"Address\":{\"City\":\"New York\",\"State\":\"NY\"}}"; // parse JSON string to JObject JObject person = (json); // Use LINQ to query JSON data string name = (string)person["Name"]; int age = (int)person["Age"]; string city = (string)person["Address"]["City"]; // Output query results ($"Name: {name}, Age: {age}, City: {city}"); // Output: Name: John, Age: 30, City: New York } }
Summarize
It is a very powerful and flexible JSON processing library that provides rich properties and methods to process JSON data. Through the above code examples and detailed comments, you should be able to master how to use serialization, deserialization, formatting, process attribute names, ignore attributes, handle null values, custom serialization, process date formats, process circular references, and use LINQ to JSON.
The above is the detailed content of common properties and methods of the C# library. For more information about the use of the C# library, please pay attention to my other related articles!