Is there a built in way in .Net AJAX to manually serialize an object to a JSON string?

前端 未结 6 1492
清歌不尽
清歌不尽 2021-02-05 21:33

I\'ve found ScriptingJsonSerializationSection but I\'m not sure how to use it. I could write a function to convert the object to a JSON string manually, but since .Net can do it

6条回答
  •  一个人的身影
    2021-02-05 22:11

    Well, I am currently using the following extension methods to serialize and deserialize objects:

    using System.Web.Script.Serialization;
    
    public static string ToJSON(this object objectToSerialize)
    {
      JavaScriptSerializer jss = new JavaScriptSerializer();
      return jss.Serialize(objectToSerialize);
    }
    
    /// The type we are deserializing the JSON to.
    public static T FromJSON(this string json)
    {
      JavaScriptSerializer jss = new JavaScriptSerializer();
      return jss.Deserialize(json);
    }
    

    I use this quite a bit - be forewarned, this implementation is a bit naive (i.e. there are some potential problems with it, depending on what you are serializing and how you use it on the client, particularly with DateTimes).

提交回复
热议问题