JSON is a lightweight format that is used in asp.net development for data exchange. In this post, Aegis professionals will make you learn how to use JSON serialization and deserialization in asp.net MVC development project. In this post, experts are sharing steps to use NewtonsoftJSON in MVC app. You can learn these simple steps and use the features accordingly.
We are introducing JSON serialization and Deserialization using Newtonsoft.JSON.dll in MVC based application.JSON (JavaScript Object Notation) is one lightweight data exchange format. JSON is "name/value" assembly. JSON structure is made up with {}, [], comma, colon and double quotation marks and it includes the following data types: Object, Number, Boolean, String and Array. Serialize means convert an object instance to an XML document. Deserialize means to convert an XML document into an object instance.
Below are the steps to use Newtonsoft JSONin MVC based application.
Steps to use Newtonsoft JSON in MVC based application
1. Download the Latest release Newtonsoft JSON dll, for download click here.
2. For give the reference ofNewtonsoft JSON dll we need to add Reference form NuGet gallery as per below Screenshot.
3. We can also add the reference form Package manager console as per below screenshot.
Now here JSON Serialization is the process of converting the state of an object into a form that can be persisted in a storage medium or transported across the processes or machines. Same way deserialization which is a process that converts the outcome of serialization into the original object. After completing the package installation for Newtonsoft JSON we can Serialize and deserialize data as per below code. Give the reference to the code by using Newtonsoft.JSON namespace in code.
For Serialize the JSON object we have to write the below code,
Here, we have two Object class RootObject and configuration class In which we have to Serialize the JSON string.
There are some crucial steps to follow. With the assistance of Aegis Softtech, engineers learn the tricks of JSon structure and applications.
Result of the Serialize Object:
1. Serialization:-
Above Screenshot is for Result of the Serialize the object in String. Using JsonConvert.SerializeObject we have converted an object into a String. Now same way we can deserialize the JSON string into the object as per below code.
Here, in above code we can deserialize the JSON string onto Object. For that we have required the object class for Deserialize, In our case we have to create RootObject class for Dserialize the JSON string as per below.
So, as per above code we get the Deserialize Result in above Object class. Also we can give settings in JsonCovert Serialize and deserialize methods like below.
Serialization Behavior
All public properties are serialized by default whenever they are used. You can set characteristics that will be ignored. You are also able to add closed-door members. Characters that are not ASCII, HTML-sensitive characters that fall inside the ASCII range, and characters that must be escaped following the RFC 8259 JSON specification are all escaped by the default encoder.
JSON is automatically minified by default. The JSON may be printed in a nice format. It is the default setting for JSON names to use the same case as .NET names. It is possible to modify the case of JSON names. The detection of circular references and the throwing of exceptions are both done by default. You can manage circular references and references that are preserved. The default behavior is to disregard the fields. It is possible to include fields.
Several default behaviors are different when you utilize System.Text.Json in an ASP.NET Core application from an indirect perspective. For further details, please refer to the defaults for JsonSerializerOptions on the web. Presented below is an example of how to serialize a JSON object in c# that illustrates the process of serializing a class that has collection properties and a user-defined type:
Serialize to UTF-8
Compared to other ways, serializing to a UTF-8 byte array is five to ten percent quicker than string-based approaches. This is because the bytes—in their UTF-8 form—do not need conversion to strings—in their UTF-16 form. The JsonSerializer must be used to serialize data to a UTF-8 byte array. Method of Serialization to UTF8 Bytes:
Serialize to Formatted JSON
Setting the JsonSerializerOptions will allow you to pretty-print the JSON output. Set the value of WriteIndented to true:
Serialize C# Object Into JSON Strings Using System.Text.Json
The system has been in use since .NET Core 3.0. By default, the framework incorporates Json into its components. The following is the official solution for serializing and deserializing JSON files developed by Microsoft:
Using Newtonsoft JSON.NET to Serialize C# Objects
Through the use of the JsonConvert object's static function known as SerializeObject(), we can convert an object into a JSON string.
How to Generate Pretty JSON Strings
Most of the time, we would want to have JSON strings that are indented or "pretty." With the help of the System, we can simply do it. Through the use of the WriteIntended attribute of the JsonSerializerOptions object, Text.Json is constructed:
Camel Case Property Names
Even though camel case is a format option that is often used, none of these libraries will format property names using camel case by default. We make sure that the PropertyNamingPolicy option in our JsonSerializerOptions object is set explicitly when we are using System.Text.Json:
How to Ignore Certain Properties When Serializing Objects
Not Taking into Account NULL Values When Serializing. On the other hand, there is a certain circumstance in which we do not want to include the attributes that have null values. In the System, we can make use of the JsonSerializerOptions object. The DefaultIgnoreCondition flag may be set using Text.Json as follows:
If Newtonsoft is being used, we will make use of the NullValueHandling property that is included under the JsonSerializerSettings.
The JSON string that is produced will not include any of the null properties, which are as follows:
How to Serialize Anonymous and Dynamic Objects
From the beginning, both libraries can appropriately handle anonymous objects.
Similarly, dynamic objects work fine as well with both System.Text.Json and Newtonsoft:
How to Control Date and Time Format
To serialize DateTime or DateTimeOffset attributes in our objects, Json will utilize the ISO-8601-1:2019 format, as shown in the following example: The date is 2017-08-24T16:59:57-02:00. However, we can personalize it by developing a converter that is unique to us:
Reference Loops
Taking into consideration the following C# models will help you comprehend what a reference loop is:
In this instance, we can see how the Employee class refers to the Department class, which in turn makes reference to the Employee class by way of its Staff property.
Options for Handling Reference Loops
The most effective method for avoiding this circumstance is to construct our models in such a manner that they do not have reference loops. JSON libraries, on the other hand, include choices that may assist us in dealing with circular references if this is not feasible. We can configure the JsonSerializerOptions for the System.Text.Json class. Refer to one of the ReferenceHandler listed values to access the ReferenceHandler property:
Convert an Object to a Minified JSON String
Through the use of Serialization, you will acquire the knowledge necessary to transform C# objects to JSON. JavaScript Object Notation, or JSON, is a format that is used for the storage and transport of data. In addition, it is used in API requests to exchange data by moving it from the API to other web apps or from the browser to the server and vice versa.
A technique known as serialization involves saving the state of an item and having the ability to reconstruct it whenever it is necessary to do so. The opposite of serialization is referred to as deserialization. Within the System, the JsonSerializer class is a built-in component that is provided by the .NET 5 framework. To convert C# objects to JSON and vice versa, the JSON namespace is used.
The JsonSerializer class that is built into the .NET 4 framework does not include any built-in functionality for converting objects to JSON. The Microsoft.Extensions package from NuGet has to be installed on your computer. Your project should contain Configuration.Json to include the System.Incorporate Text.Json. JsonSerializer into your project so that it can be used to convert objects to JSON and vice versa.
Convert an Object to a Formatted JSON String
Within the context of the JsonSerializer class, the following example illustrates the process of converting an object into a JSON string that has been minified. Method of serialization:
Convert a List to a JSON String
The following converts a list collection of objects to a JSON array.
Convert an Object to a UTF-8 String
When compared to the string technique, serialization to a byte array that accepts UTF-8 is a little bit quicker. Since the bytes of utf-8 are not necessary for the conversion to strings of utf-16, this is the case. The following example demonstrates how to use JsonSerializer to convert an object into a JSON string that has been converted to a smaller size procedure known as SerializeToUtf8Bytes
Advantages Serialization - Deserialization:-
1. The main benefit is the speed in populating an object as opposed to querying multiple tables in the case of database storage.
2. Simplicity in coding for serialization and deserialization is another benefit.
Using DataContractJsonSerializer
To serialize and deserialize JSON, the DataContractJsonSerializer class is designed to assist. Through the use of the class, we can convert an object into JSON data and then deserialize the JSON data back into an object. Within the namespace System, it may be found existing. Within the assembly System, you will find the Serialization.Json file while it is running .dll file for serialization.
Using JavaScriptJsonSerializer
It is possible to serialize and deserialize JSON with the assistance of a class called JavaScriptSerializer. Furthermore, it may be found under the namespace System.The Web.Script.System.Web.Extensions.dll is the assembly file that has serialization capabilities. The Serialize method is what you should use to convert a .Net object into a JSON string. Through the use of the Deserialize
How to get the Library
As an element of the common framework, the library is included in .NET Core 3.0 and subsequent versions of the framework. When using.NET 6 and later versions, the source generation functionality is already included in the common framework as a standard component. Installation of the System is required for framework versions that are older than .NET Core 3.0. The Text.Json package under NuGet. Supported by the package are:
- Standard 2.0 and subsequent versions of.NET
- Framework 4.6.2 and subsequent versions of.NET
- Core.NET version 2.1 and later
- At least.NET version 5
Namespaces and APIs
As for the System.Words.Every single entry point and the primary types are contained inside the JSON namespace. As for the System.Using Text.Json.Serialization namespace is comprised of properties and application programming interfaces (APIs) that are designed to accommodate complex situations and customizations that are particular to serialization and deserialization.
HttpClient and HttpContent extension methods
It is normal practice to perform actions such as serializing and deserializing JSON payloads from the network. You may do these activities with only one line of code by using the extension methods that are available on HttpClient and HttpContent. When it comes to JsonSerializerOptions, these extension methods make use of the web defaults.
An illustration of the usage of HttpClientJsonExtensions is shown in the following example.HttpClientJsonExtensions and GetFromJsonAsync are two examples. Async Posting of JSON:
Reflection vs Source Generation
During runtime, System.Text.Json will automatically collect the information it needs to access the attributes of objects for serialization and deserialization. This is accomplished via the phenomenon of reflection. System.Text.Json can take advantage of the C# source generation function to enhance efficiency, decrease the amount of private memory that is used, and allow assembly trimming, which results in a smaller size for the application.
Explanation of Serialize and Deserialize using Python
This format, known as JSON, is used to encode objects inside a string. A string is converted into an object by the process of serialization, while the opposite of serialization is deserialization, which is the process of converting a string into an object.
The data to be in the form of byte strings for them to be sent or stored in a file; yet, complex things are seldom in this format. For this application, serialization may transform these complicated objects into byte strings. Once the byte strings have been communicated, it will be necessary for the recipient to extract the original object from the byte string for further processing. This process is referred to as deserialization.
If you have an item, for example:
In the process of serializing into JSON, the string "foo: [1, 4, 7, 10], bar: "baz" will be converted into a string.
"foo":[1,4,7,10],"bar":"baz"', which may be stored or sent by wire to whatever location they are intended for. This string may then be deserialized by the recipient, which will allow them to get the initial object. The foo is [1, 4, 7, 10], and the bar is "baz".
Serialization using Pickle
Differences in Default Behavior
To emphasize predictable behavior, JSON was designed to be strict by default. It does not allow the caller to make any guesses or interpretations. The library was purposefully created in this manner to maximize both performance and security. A significant number of the following particular variances in default behavior may be traced back to this original difference in design.
Case-insensitive Deserialization
Case-insensitive property name matching is performed by default by Newtonsoft.Json throughout the deserialization process. As for the System.Words.Because it does an exact match, the default JSON format is case-sensitive, which results in improved speed. The article "Case-insensitive property matching" provides information on how to do matching that is not sensitive to the case.
If you are doing so to get behavior similar to that of Newtonsoft.Json, you may use Text.Json indirectly by using ASP.NET Core. When ASP.NET Core makes use of System.Text.Json, jsonconvert.serializeobject c# does so in a manner that defines the settings for camel-casing property names and case-specific matching. As an additional feature, ASP.NET Core provides the deserialization of quoted numbers by default.
Scenarios using JsonSerializer
The following are some examples of situations that are not handled by the built-in capability. Nevertheless, there are workarounds that may be used. The solutions consist of custom converters, which may not give total parity with the capabilities of Newtonsoft.Json because of their limitations. Exemplifications in the form of sample codes are supplied for some of them. During the migration process, you will need to make updates to your.NET object models or other code changes if you depend on certain Newtonsoft.Json functionalities.
It is not feasible or practicable to find solutions for some of the cases that are in the following list. If you remain dependent on some Newtonsoft.Json functionalities, migration will not be feasible without considerable modifications.
Allow or write numbers in quotes
Numbers that are represented by JSON strings (which are enclosed in quotation marks) may be serialized or deserialized using JSON. It is possible, for instance, for it to accept the following: {"DegreesCelsius":"23"} rather than {"DegreesCelsius":23}. Therefore, the behavior may be enabled in the System. Please set the JsonSerializerOptions for Text.Json.Make use of the [JsonNumberHandling] attribute, or change the NumberHandling property to either WriteAsString or AllowReadingFromString.
Whereas you are using System, you can achieve behavior similar to that of Newtonsoft.Json by utilizing Text.Json indirectly via the use of ASP.NET Core. There is no need to do anything more. The usage of System.Text.Json by ASP.NET Core results in the specification of web defaults, and web defaults permit the use of quoted numbers.
Specify the constructor to use when deserializing
When deserializing to a POCO, you can choose the constructor constructor to invoke by using the Newtonsoft.Json [JsonConstructor] property. On top of that, Json has a property called [JsonConstructor]. Check out the article on immutable types and records for more details.
Preserve object references and handle loops
Value-based serialization is the default behavior of Newtonsoft.Json. For instance, if an object has two properties, each of which has a reference to the same Person object, then the values of the properties that belong to that Person object will be repeated in the JSON. There is a feature on JsonSerializerSettings called PreserveReferencesHandling that allows you to serialize objects based on their references:
It is necessary to provide identifying information in the JSON that is prepared for the initial Person object. Instead of containing property values, the JSON generated for the second Person object includes a reference to the identifier that was used to construct the object. There is also a feature in JSON called ReferenceLoopHandling that allows you to tolerate circular references rather than throwing an exception. The purpose of this is to maintain references and manage circular references inside the System. Please set the JsonSerializerOptions for Text.Json.Regarding the ReferenceHandler to Store.
The Preserve setting is the same as the PreserveReferencesHandling = PreserveReferencesHandling condition expression. Everything is in Newtonsoft.Json format. The behavior of the IgnoreCycles option is similar to that of Newtonsoft. Ignore the JSON ReferenceLoopHandling request. One distinction is that the System is different. As an alternative to ignore the object reference, the JSON implementation substitutes reference loops with the null JSON token. See the article on "Ignore circular references" for more details.
Similar to the Newtonsoft.System, also known as the Json ReferenceResolver.Serialization that uses Text.Json. When serialization and deserialization are performed, the ReferenceResolver class is responsible for defining the behavior of maintaining references.
Deserialize String Enum Values
The deserialization of string enum values is not supported by System.Text.Json by default, although Newtonsoft.Json does offer this functionality. Take, for instance, the code that follows, which generates a JsonException:
Deserialization of Object Properties
During the process of deserialization to Object, Newtonsoft.Json:
The stored text, long, double, boolean, or DateTime should be returned as a boxed object. This function infers the type of primitive values that are included in the JSON payload, assuming that they are not null. One kind of JSON value is referred to as a primitive value. Primitive values include a JSON integer, string, true, false, or null.
For complicated values included inside the JSON payload, returns either a JObject or a JArray. Comprised of JSON key-value pairs enclosed within brackets (\}) or lists of values enclosed inside brackets ([]), complex values are groups of values. In addition to the attributes and values included inside the braces or brackets, extra properties and values may also be present. If the payload contains the null JSON literal, then this function will return a null reference.
Deserialize Null to Non-Nullable Type
When the following situation occurs, Newtonsoft.Json does not throw an exception:
The value of NullValueHandling is set to Ignore, and the JSON file includes a null value for a value type that is not nullable. This occurs throughout the deserialization process. The System is in the same situation as before. This is an exception that is thrown by Text.Json. It is the comparable null-handling setting in the System environment.JsonSerializerOptions is comprised of Text.Json."IgnoreNullValues" is set to true). If you are the owner of the target type, the most effective solution would be to make the property in question nullable (for instance, convert int to int?).
Deserialize to Immutable Classes and Structs
Since it is possible to employ constructors that contain arguments, JSON is capable of deserializing to immutable classes and structs. Make use of the [JsonConstructor] property when working with System.Text.Json to express the use of a parameterized constructor. Immutable records are also supported as deserialization targets in C# 9, which means that they cannot be changed.
Conclusion
Hope you can now use JSON serialization and deserialization in asp.net MVC development and design intuitive applications. Aegis experts have also shared advantages of serialization and deserialization. Aegis Softtech is a leading asp.net and Java development company, if you have any specific requirement related to these section feel free to contact us.
For further information, mail us at [email protected]