I recently started writing my own projects, and finally mustered up the courage to take what I thought was a big step!
Let me share with you the general helper class first. The first one is a class that converts Object into a json sequence. There are many on the Internet, but after I tried it, most of them cannot be used, or there are various bug. In fact, there is a good class in C# that can solve this problem. It is the JavaScriptSerializer class. With this class, you can convert your object type into json and output it to the front desk with just a few lines of code. Got it!
First we need to reference the System.Web.Extensions dll in the project before we can use the JavaScriptSerializer class
The next step is the code, which is very simple.
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Script.Serialization;using System.Data;namespace CodeHelper { public class JsonHelper { /// <summary> /// 对象转JSON /// </summary> /// <param name="obj">对象</param> /// <returns>JSON格式的字符串</returns> public static string ObjectToJSON(object obj) { JavaScriptSerializer jss = new JavaScriptSerializer(); try { return jss.Serialize(obj); } catch (Exception ex) { throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message); } } } }
The above is the detailed content of JavaScriptSerializer implementation class. For more information, please follow other related articles on the PHP Chinese website!