Introduction to JSON
1. What is JSON?
JSON (JavaScript Object Notation) is a lightweight data exchange format. Its syntax is based on JavaScript object notation, simple and easy to read, and is supported by many programming languages. Although it comes from JavaScript, it does not rely on JavaScript, and many languages (such as Python, Java, C#, PHP, etc.) can parse and generate JSON.
Common uses:
API data interaction: JSON is a common format when passing data between the client and the server, especially when interacting with the front and back ends.
Configuration files: Many applications use JSON to save configuration files (such as .json files).
Data persistence: Use JSON in a database or file system to store structured data.
2. Basic syntax structure of JSON
The data structure of JSON is very simple, mainly including the following two types:
Object: A set of key-value pairs surrounded by curly braces {}. The key is a string and the value can be any legal JSON data type.
Array: A set of values surrounded by square brackets [], which can be of any JSON type.
Example:
{ "name": "John", "age": 30, "isStudent": false, "courses": ["Math", "Science"], "address": { "city": "New York", "zipcode": "10001" } }
Basic elements of JSON:
String: Wrapped in double quotes, such as "name": "John"
Number: can be an integer or a floating point number, such as "age": 30
Boolean: true or false
Array: an ordered list of values wrapped in square brackets []
Object: An unordered set of key-value pairs wrapped in curly braces {}
Null value: null
It is not difficult to see that JSON is essentially composed of three main elements:
Object: A collection of key-value pairs, similar to a dictionary. A JSON object is represented by {}, containing key-value pairs, the key must be a string, and the value can be any legal JSON element (such as an array, object, or base value).
Array: an ordered set of elements, similar to a list or an array (does not represent an array of C#, but only reflects an ordered set). JSON arrays are represented by [], and each element in the array can be any legal JSON element (such as an object, array, or base value).
Basic value: The most basic element of JSON, which can be a string, a number, a boolean value, or null. This part of the data can no longer contain other child elements.
This is very important: because fully analyzing these three elements themselves and their relationships is the key to JSON processing. Many JSON libraries also consider these three concepts to implement.
3. Advantages of JSON (function)
The reason why JSON has become the preferred format for data exchange is inseparable from its many advantages:
Lightweight: Compared with formats such as XML, JSON takes up less volume and has a simpler structure.
Good readability: easy to read by humans, and parsing programs are also easy to write.
Supports rich data types: it can directly represent common data structures such as objects, arrays, strings, numbers, and Boolean values.
Widely supported: Almost all programming languages provide libraries or built-in functions for parsing and generating JSON.
Standardized format: JSON format has clear standards to ensure cross-language and cross-platform compatibility.
High flexibility: It can nest any complex objects and arrays, suitable for complex data structures.
4. Common usage scenarios of JSON
API Communication
In modern web development, front-end communication often relies on JSON. When a client sends HTTP requests, the data is usually passed in JSON format, and the server also returns the data through JSON format. Here is a simple example:
Request body (data sent by the client to the server):
{ "username": "john_doe", "password": "123456" }
Response body (data returned by the server):
{ "status": "success", "message": "Login successful", "token": "abcdef123456" }
Configuration File
The JSON format is often used to store configuration data because it is easy to read and modify. For example, an application's configuration file might be as follows:
{ "app_name": "MyApp", "version": "1.0.0", "settings": { "theme": "dark", "language": "en" } }
Local data storage
In front-end development, JSON is often used to store data locally (such as the browser's localStorage or sessionStorage).
Data serialization
When saving an object or data structure to a file or database, it is usually necessary to serialize it into a string format, and JSON is one of the commonly used serialization formats.
Mapping relationship with C# type
In C#, the basic elements of JSON have a direct correspondence with the corresponding data type.
1. String
JSON: Strings are wrapped in double quotes to represent text data.
Example: "name": "John"
C# corresponding type: string
In C#, JSON's string type is directly mapped to a string type.
Example:
string name = "John";
2. Numbers
JSON: Numbers can be integers or floating-point numbers, representing data of numerical types.
Example: "age": 30
C# corresponding types: int, float, double
In C#, integers can be mapped to int, and floating point numbers can be mapped to float or double, and the type can be selected according to the specific needs.
Example:
int age = 30; float price = 29.99f; double pi = 3.14159;
3. Boolean value
JSON: Boolean value is expressed as true or false.
Example: "isStudent": false
C# corresponding type: bool
In C#, boolean values are mapped to bool type.
Example:
bool isStudent = false;
4. Array
JSON: An array is an ordered list of values wrapped in square brackets []. Each element in the array can be of any JSON type.
Example: "courses": ["Math", "Science"]
C# corresponding type: List<T> or array T[]
In C#, JSON arrays can be mapped to List<T> (generic list) or to a normal array T[], where T is the type of elements in the array.
Example:
List<string> courses = new List<string> { "Math", "Science" }; // orstring[] coursesArray = { "Math", "Science" };
5. Object
JSON: Objects are an unordered set of key-value pairs wrapped in curly braces {}. Each key must be a string and the value can be of any JSON type.
Example: "address": { "city": "New York", "zipcode": "10001" }
C# corresponding type: custom class or Dictionary<string, T>
In C#, JSON objects can be mapped into custom classes, and properties in the class correspond to key-value pairs in the JSON object. You can also use Dictionary<string, T> to represent a set of key-value pairs, where T represents the type of value.
Example (using custom class):
class Address { public string City { get; set; } public string Zipcode { get; set; } } Address address = new Address { City = "New York", Zipcode = "10001" };
Example (using a dictionary):
Dictionary<string, string> address = new Dictionary<string, string> { { "city", "New York" }, { "zipcode", "10001" } };
6. Null value
JSON: The null value is expressed as null.
Example: "middleName": null
C# corresponding type: null
In C#, the null of JSON corresponds to the null value in C#. It can be applied to any nullable type (such as reference types and Nullable<T>).
In C#, the basic elements of JSON can be mapped to the corresponding C# data type. This mapping allows us to easily process JSON data and interact with objects and types in C#.
6. How to process JSON data
What is serialization/deserialization
We must first lay the groundwork for what is serialization/deserialization
SerializationandDeserializationIt is a process of converting objects and data between different formats, mainly used in scenarios such as data persistence and network transmission. In C#, our data is generally stored in memory in the form of objects, but the memory data cannot be saved for a long time. The data will be gone after you shut down or when the program is closed. So how can we save the data?
The answer is serialization. What we often use is to serialize objects into JSON (of course not only JSON, but JSON is more commonly used), so we can add it (this one).ThatTo put it more clearly, strings. JSON is mostly in the form of strings, but you can understand that it is a string with a certain format or rules) that is convenient to save on disk or pass to others through the network.
Of course, converting JSON into an object in memory is deserialization. A common scenario is to read JSON format configuration files, read them from disk first and then deserialize them into objects, so we can operate this object very conveniently.
How to do it?
Most programming languages provide libraries or built-in functions for parsing (deserializing) and generating (serializing) JSON data.
C# provides and (third-party libraries) to handle JSON.
I recommend using (NuGet Gallery | 13.0.3), this can be said to be the most popular and most powerful library in the C# environment. After about twenty years of development, it supports most .net environments and is currently ranked first among all nuget packages.
Common usage
1. Use the method to convert a C# object to a JSON string.
using ; public class Person { public string Name { get; set; } public int Age { get; set; } public bool IsStudent { get; set; } } Person person = new Person { Name = "John", Age = 30, IsStudent = false }; // Serialize to JSONstring json = (person); (json);
Get (this is a string, including curly braces at the beginning and end, mentioned earlier that {} represents an object, with unordered key-value pairs inside)
{"Name":"John","Age":30,"IsStudent":false}
2. Use <T> to deserialize a JSON string into a C# object.
//The \ here is an escape character, not the content of the string itselfstring json = "{\"Name\":\"John\",\"Age\":30,\"IsStudent\":false}"; // Deserialize to an objectPerson person = <Person>(json); (); // Output "John"(); // Output 30
3. Convert JSON arrays to C# collections (such as List<T>).
string jsonArray = "[{\"Name\":\"John\",\"Age\":30},{\"Name\":\"Jane\",\"Age\":25}]"; // Deserialize to List<Person>List<Person> people = <List<Person>>(jsonArray); foreach (var person in people) { ($"{}, {}"); }
John, 30
Jane, 25
4. Handle nested objects
If a nested object is included in JSON, the nested structure can be automatically deserialized.
public class Address { public string City { get; set; } public string Zipcode { get; set; } } public class Person { public string Name { get; set; } public Address Address { get; set; } } string nestedJson = "{\"Name\":\"John\",\"Address\":{\"City\":\"New York\",\"Zipcode\":\"10001\"}}"; // Deserialize nested JSONPerson person = <Person>(nestedJson); ($"{} lives in {}, {}");
,JObject,JArray,JValue
The above mentioned basic components of JSON: objects, arrays, and basic values. This corresponds to the three types of JObject, JArray, and JValue provided by newtonjson. Where is there a JToken? This JToken is an abstract type of three types, and the latter three inherit from the former.
Why are these classes mentioned? Because they are more flexible!
Pay attention to the above example. When we deal with a JSON, we need to declare a type first. Sometimes we declare this type may rarely be used, so it seems unnecessary for us to declare a type at this time.
Or the structure of this JSON data is not fixed or dynamic. So we use the above type.
string jsonString = "{\"name\": \"Alice\", \"age\": 25}"; // Use JObject to parseJObject obj = (jsonString); // Dynamic access to fieldsstring name = (string)obj["name"]; int age = (int)obj["age"]; ($"Name: {name}, Age: {age}");
Please see that JSON represents an object. If this type is not commonly used, then we directly think that it is a JObject type. In this way, we convert it to a JObject type and then use the indexer to get the data we need directly.
As mentioned above, we know that this is an object, so we use the JObject type, so we don’t even know this? It doesn’t matter! Take out our JToken type, which is the parent class of three subclasses, contains the behavior of all subclasses, and can represent all JSON concepts, whether it is an object, array, or basic value.
using ; string jsonString = @"{ 'person': { 'name': 'Alice', 'age': 25, 'address': { 'city': 'Wonderland', 'zipcode': '12345' }, 'phones': ['123-456-7890', '987-654-3210'] } }"; // parsed as JTokenJToken token = (jsonString); // Dynamic access to nested fieldsstring name = (string)token["person"]["name"]; string city = (string)token["person"]["address"]["city"]; string phone = (string)token["person"]["phones"][0]; ($"Name: {name}, City: {city}, First Phone: {phone}");
using ; string jsonString = @"{ 'name': 'Alice', 'age': 25, 'address': { 'city': 'Wonderland', 'zipcode': '12345' }, 'hobbies': ['reading', 'chess', 'running'] }"; // Use JToken to parseJToken token = (jsonString); // Dynamic access to fields in objectsstring name = (string)token["name"]; int age = (int)token["age"]; // Dynamic access to nested objectsstring city = (string)token["address"]["city"]; string zipcode = (string)token["address"]["zipcode"]; // Dynamically access elements in arraystring firstHobby = (string)token["hobbies"][0]; string secondHobby = (string)token["hobbies"][1]; // Output result($"Name: {name}, Age: {age}"); ($"City: {city}, Zipcode: {zipcode}"); ($"First Hobby: {firstHobby}, Second Hobby: {secondHobby}");
Type conversion (for JToken or its subclass)
Not only does it support accessing JSON data through type casting, it also provides a more convenient way to perform type conversion. These methods can avoid potential abnormal risks when type casting and provide clearer code expression.
The following commonly used type conversion methods are provided
<T>() method (applicable to basic types)
Value<T>() is a generic method provided by JToken that can safely convert the value of JToken to a specified type. If the type conversion fails, it does not throw an exception, but returns the default value of the type.
Suitable for scenarios where you want to avoid explicit type casting and want your code to be more concise and safe.
JToken token = (@"{ 'name': 'Alice', 'age': 25 }"); string name = token["name"].Value<string>(); // Safe type conversionint age = token["age"].Value<int>(); // Convert to int($"Name: {name}, Age: {age}");
When using Value<T>() for conversion, if the value does not exist or the conversion fails, it will return the default value of the type (such as string will return null, int will return 0), and will not throw an exception like type cast.
<T>() method
ToObject<T>() is another common method that allows converting a JToken to a specific object or type. It works for scenarios where you want to deserialize JSON data to specific types (such as classes or structures) in C#.
The ToObject<T>() method is transformed by deserialization, so it is suitable for complex data structure conversion.
// Define a class corresponding to JSON datapublic class Person { public string Name { get; set; } public int Age { get; set; } } JToken token = (@"{ 'name': 'Alice', 'age': 25 }"); // Deserialize JTokens into specific Person objectsPerson person = <Person>(); ($"Name: {}, Age: {}");
Suitable for handling complex JSON data structures, it can directly convert the entire JSON structure into a C# object.
Its flexibility makes it easy to create C# class objects from JSON data without manually extracting each field.
<T>(out T result) method
This is a relatively safe way to access. TryGetValue tries to get the value of the specified type from the JToken and indicates whether it is successfully obtained by returning a boolean value.
It is suitable for safe conversion operations when you are uncertain about the JSON data structure or type, avoiding throwing exceptions.
JToken token = (@"{ 'name': 'Alice', 'age': 'not an integer' }"); // Try to get the value safelyint age; bool success = token["age"].TryGetValue<int>(out age); if (success) { ($"Age: {age}"); } else { ("Failed to get a valid integer for age."); }
A safe type conversion method suitable for use when JSON data is unreliable or complex structures.
It returns the result through the out parameter, which can avoid exceptions.
Methods provided by cast vs
Explicit Casting
Allows direct casting, such as (string)token["name"] or (int)token["age"]. This method is relatively simple, but if the type does not match or the value does not exist, an exception will be thrown.
Summarize
Value<T>() method: Provides a safe type conversion method, no exception is thrown, suitable for handling simple data access scenarios, and the code is concise.
ToObject<T>() method: It is suitable for converting JSON directly into C# objects, especially for complex JSON structures, which can reduce the workload of manually extracting each field.
TryGetValue<T>() method: Provides a safe way to get values in JSON data, suitable for use when the data structure or type is uncertain, preventing exceptions from occurring.
This is all about this article about using JSON in C#. For more related content on using JSON in C#, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!