Conversion between Object and Json in C,
// Create a class, which has two methods
Using Newtonsoft. Json;
Namespace System
{
Public static class JsonExtension
{
/// <Summary>
/// Convert the object to a JSON string
/// </Summary>
/// <Param name = "o"> Object </param>
/// <Returns> JSON string </returns>
Public static string ToJSON (this object o)
{
If (o = null)
{
Return null;
}
Return JsonConvert. SerializeObject (o );
}
/// <Summary>
/// Convert Json text into an object
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
/// <Param name = "input"> </param>
/// <Returns> </returns>
Public static T FromJSON <T> (this string input)
{
Try
{
Return JsonConvert. DeserializeObject <T> (input );
}
Catch (Exception ex)
{
Return default (T );
}
}
}
}
// Use
User user = new User ();
User. UserName = "tom ";
User. Age = 22;
User. Sex = 1;
User. Like = "PLAY ";
Var json = JsonExtension. ToJSON (user); // convert the object to Json
String user = "{\" UserName \ ": \" tom \ ", \" Age \ ": 22, \" Sex \ ": 1, \" Like \": \ "PLAY \"} "; // escape character is used here
Var entity = user. FromJSON <User> (); // convert Json to object