Conversion between object and JSON in C #

Source: Internet
Author: User
Tags tojson

Create a class that has two methods

Using Newtonsoft.json;

Namespace System
{
public static Class Jsonextension
{
<summary>
Convert an object to a JSON string
</summary>
<param name= "O" > Objects </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 to Entities
</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);//object to JSON

String user = "{\" username\ ": \" tom\ ", \" age\ ": 22,\" sex\ ": 1,\" like\ ": \" play\ "}";//use escape character here
var entity = user. Fromjson<user> ();//json to entity object

Source: https://www.cnblogs.com/ButterflyEffect/p/6134401.html

Conversion between object and JSON in C #

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.