I recently talked about how to create C# entities from Json in a previous post. As a continuation to that post I will show how to perform deserialization of a JSON string to an instance of a C# class created from this previous post. Its important to note that the act of deserialization will become even more useful in the future as JSON becomes the defacto form of data exchange. Therefore we will create a generic method that is able to parse any type of C# class.
The following steps will need to be followed
1. Add a reference to Newtonsoft.Json preferebly from nuget
Install-Package Newtonsoft.Json
2. Write the method to perform the Json parsing as follows
public static T ParseSerializedResponse<T>(string serializedResponse) where T:class { return !string.IsNullOrEmpty(serializedResponse)? JsonConvert.DeserializeObject<T>(serializedResponse): default(T); }
From the snippet above if the Json string is not well formed and hence cannot be deserialized a null object will be returned otherwise the deserialized equivalent will be returned.
3. The usage of this method is as simple as
ParseSerializedResponse<Rootobject>(serializedResponse);
Any comments are welcome on performing this parsing in a more efficient way if any.