Memory dumps of a developer

Articles and tutorials on .NET Core, ASP.NET MVC, Kendo UI, Windows 10, Windows Mobile, Orchard

  • Json.NET - Converting Collections

    Json.NET supports serialization and deserialization of array, generic list, dictionaries and custom collections too.

    Serialization

    To serialize collection, you needs to call the SerializeObject method and pass the collection object to it as the parameter and Json.NET converts it to json string automatically without needing any other configuration.

    In the example given below, we have created a class User with two properties, Name and Age. And in the main method we are intializing a list of users and to serialize the list, we are passing it to the SerializeObject method in JsonConvert class.

    string jsonText = JsonConvert.SerializeObject(usrs, Formatting.Indented);

    Deserialization


  • Json.NET - Converting JSON to XML and Vice Versa

    Json.Net supports the conversion from XML to JSON and JSON and XML vice versa.

    JSON to XML Conversion.

    We are going to use 

    DeserializeXNode(string json, string nodeName)

    method defined in JsonConvert class to convert JSON to XML It will return an XNode object containing the XML. You will need to import System.Xml and System.Xml.Linq namespaces for this sample to work correctly


  • Json.NET - Using JsonSerializer Class

    In the previous post, I have detailed the serialization and deserialization functionalities using the Serialize and Deserialize methods in JsonConvert class. These methods are built on top of JsonSerializer class which is doing all the heavy lifiting during the conversion process under the hood. 

    In this I will show you how to use JsonSerializer class for doing the conversion. One advantage of using this class is that we have more control over the conversion process. It exposes different properties through which we can control how Json.Net will serialize/deserialize the json

    So let's add one more property EffectiveDate which is a DateTime field to our class from the previous post 

    In this example, I am using JsonSerializer class instead of JsonConvert class for doing the serialization. Unlike the latter one, using this allows me to write JSON directly to the stream using StringWriter and JsonTextWriter. Like the JsonConvert class, JsonSerializer also has a number of properties for customizing the serialization process and it allows the developer to have more control over it.  

    Also in this example, I have used a converter for serializing the date, JavaScriptDateTimeConverter. If I serialized it without usng the converter the output would be like the one given below

    {"ColorId":1,"ColorName":"Green","EffectiveDate":"2016-04-01T00:00:00"}

    The date format will be in ISO date format But if you want to have the JavaScript Date object in your json, you can use the JavaScriptDateTimeConverter for that.


  • Json.NET - Handling Errors

    Json.NET supports two type of error handling, using the Error event and using OnErrorAttribute

    The methods allows you to catch errors and allows it to handle it by you and continues the serialization process or it bubbles up the chain as an unhandled one

    The Error event is defined in the JsonSerializer and this event fires whenever there is an error during serialization of deserialization process. You can use the JsonSerializerSettings instance to set the Error event.

    In this example, I have created a delegate for the error event, which will add the error to a collection. Here, I have intentionally entered a string for the DateTime field so that an exception will occur during the conversion process. When the exception occurs, it's catched by our delegate, adds it to the collection and set the Handled property to true so that it's not bubbled up.

    You can see that eventhough the exception has occured, it doesn't stop the conversion process with the rest of the items.

    OnError Attribute

    You can use this attribute on the class like any other attribute so far in this series. To use this one, just decorate the method you want to handle the error with the attribute [OnError] as shown below

    [OnError]
    internal void OnError(StreamingContext context, ErrorContext errorContext)
        {
            errorContext.Handled = true;
        }
    


  • Json.NET - Logging And Debugging

    Logging feature can be implemented in Json.Net by making use of the ITraceWriter interface. MemoryTraceWriter and DiagnosticsTraceWriter are the two implementations of ITraceWrite available in Json.Net. The former implementation keeps the messages in memory and is not persisted in any storage medium and is useful for doing basic debugging. The later one writes messages to the tracelisteners that our application is using. Advantage of using TraceListeners is that the information is persisted and is available for reference even after the application is closed.

    In this example, I am going to implement the MemoryTraceWrite for logging information as well as error messages

    First I have created an instance of the ITraceWriter and set it to the TraceWriter property in JsonSerializerSettings instance. 

    Also you implement your own trace writers by creating new logger classes by inheriting the ITraceWriter interface. By doing this way, you will be able to integrate it with your own logging framework,


  • Json.NET - Conditional Serialization

    In the last post, I have showb you how to use DataMember and JsonIgnore attributes for skipping properties from getting outputed to json. But in some case we need to omit it based on conditions and these apporaches is not to going to help you

    In Json.NET we can do this by adding a method whose name will start with ShouldSerializeMethod and append the name of the property to it.

    In the following example I have a class with two properties, Username and Password and I didn't want the password to be sent across. So I created a method ShouldSerializePassword(ShouldSerialize + name of the property that needs to be omitted).

    So by manipulating the return value of the method, we can conditionally skip members from the resulting json.


  • Json.NET - Reducing the Payload of Data Transferred

    While developing web apps, it's the duty of we, developers to make sure that we are sending only the required data back and forth. Otherwise it can cause a performance hit for for your application. Let's assume that you hava class that contains a lot of properties and in a page you are using a couple for properties in that instance for showing the data in the page. In this case if we send the whole instance to client, we are actually sending lot of unwanted data to the client consuming bandwidth and also making the page slower.

    Json.net has got lot of options baked into the framework to get through these kind of situations. Json.Net will serialize all the properties and fields from the class to create the json. You can restrict that in two ways

    1. JsonIgnore Attribute

    If you want Json.net to ignore some properties while writing to JSON, you can decorate that property with JsonIgnore attribute as shown below.


  • Json.NET - Handling Default Values

    In the earlier post we have seen that we can use the NullValueHandling property to handle null values during serialization and omit it from the resulting json string.

    There is another feature called Default Value Handling, where we can specify a default value for the attribute and instruct Json.Net to use that value during conversion operation when the underlying property is empty.

    The NullValueHandling  property is available in the JsonSerializationSettings class and it accepts 4 values.

    1. DefaultValueHandling.Ignore

    When we set this property, during serialization, if the property names matches the default values of the data type, like Min Value for Date, Null for nullable fields, then those field will be omitted from the resulting string

    In the above example, I have specified null value for ColorCode and min value for effective date. So both of them are omitted from the json output string.

    If we haven't set it to ignore, then we will the output as shown below.

    {"ColorId":1,"ColorName":"Red","EffectiveDate":"0001-01-01T00:00:00","ColorCode":null}

  • Json.NET - Customizing Serialization Settings

    We can control the serialization/deserialization process using JsonSerializer class. Let's explore some of them

    Ignore Null Values

    In Json.Net we have the option to ignore values. Somtime during conversions, properties can be null and while doing the serilization, Json.Net will include that also in the result string.

    In the program we are not passing any data to ColorCode attribute and after serialization it's coming as null in produced string.

    So handle this one, I have created a new instance for JsonSerializer and set the NullValueHandling property to NullValueHandling.Ignore. When it's set to ignore, it will omit the property from writing to the string if the value is null. The value of the NullValueHandling attribute is set to NullValueHandling.Include by default and that's why it exists in the string in the earlier example.

    Missing Member Validation

    During deserialization we can prevent the process from completing if there are any missing members in the json input string. For example in the below example, there is no entry for the ColorName property in the string. But in the class it's decorated with Mandatory attribute. So if you want Json.NET to raise the exception during such scenario, you need to set the MissingMemberHandling property to MissingMemberHandling.Error so that the conversion won't go through successfully.

    By default the value MissingMemberHandling is set to MissingMemberHandling.Ignore, so that no exception are thrown even if members are missing


  • Json.NET - Serializing and Deserializing Data

    In this post, I am going to explain the process of converting json data to a .NET object and vice versa using Json.NET. 

    We will be using the SerializeObject and DeserializeObject methods in JsonConvert class for doing this. These methods encapsulates all the heavy listing done by JsonSerializer class which is actually doing the conversion under the hood.

    In the example given below, I am trying to convert a .NET object into json sting using the SerializeObject method. I have created a class which contains two string properties for Id and Name, created an instance of it and intialized the values.

    Serializing Data

    To use Json.NET , first you need to install the package via NuGet. I have already wrote a post on that subject earlier and you can refer it here. Then you need to import the namespace Newtonsoft.Json into the program.

    After that you can call the SerializeObject in JsonConvert class to do the conversion and the resulting json string is store in jsonOutput.

    Syntax

    JsonConvert.SerializeObject(T inputclass);

    Usage 

    String jsonOutput = JsonConvert.SerializeObject(clsInfo);

    When we call the SerializeObject method, Json.Net will take the properties name from the class definition to create the keys with the same name is the resulting json. The values for these keys are taken from the values in properties of the instance and that's the json string is formed.

    If you look at the class definition closely, you can see that I have specified string as type for both the properties and when the json string is formed, the value is enclosed in the double quotes. Let's change the type of the ColorId property to int and will see how will our json string look like

    If you look at the output now, the ColorId property is now not enclosed in double quotes. Json.net will always consider the type of property and based on that only it's building the json string.

    Deserializing Data

    For deserialization, we will make use of the DeserializeObject  method in JsonConvert class. It expects the json string that need to be converted as well the type to which it needs to be converted. Here also I'm making use of the class with two string properties and the magic happens here in this statement.

    Usage

    ColorInfo clsInfo = JsonConvert.DeserializeObject<ColorInfo>(jsonOutput);

    Syntax

    JsonConvert.DeserializeObject<T>(string inputString);

    As we done in the case of serialization, let's change the property of the ColorId property to int and see how deserialization goes

    You will be surprised that there are no error and conversion happened successfully. That's because Json.net will handle that conversion internally there by producing the desired output.