开发者

C# JSON to LIST extension method

From Scottgu's post i got the code to Serialize a collection to JSON object.(i)How to convert the JSON object back to List? (ii) I did not find JavaScriptserializer in System.Runtime.Serialization will the only code work for VS 2010?

ScottGu's snippet

namespace ScottGuHelper.JSON
{
  public static class JSONHelper
  {
      public static string ToJSON(this object obj)
      {
        JavaScriptserializer serializer=new JavaScriptserializer();
        return serializer.serialize(obj);
      }

     public static string ToJSON(this object obj,int recursionDepth)
     {
       JavaScriptserializer serializer=new Javascriptserializer()开发者_StackOverflow社区;
       serializer.RecursionLimit=recursionDepth;
       return serializer.serialize(obj); 
     }

 }
}


Reference System.Web.Extensions.dll. It is in the System.Web.Script.Serialization namespace. On the MSDN page for JavaScriptSerializer you'll see where it is located and for which versions of .NET it is available.


Refer System.Web.Script.Serialization for JavaScriptSerializer.

Write an extension method to call Deserialize the object.

    public static T JSONtoList<T>(this object jsonObj)
    {
        JavaScriptSerializer _jsserializer = new JavaScriptSerializer();
        return _jsserializer.Deserialize<T>(jsonObj as string);
    }

Hope this helps.(Code is not tested).


Have a look to the Deserialize method of the same JavascriptSerializer class.

The class is in the System.Web.Script.Serialization namespace

You can find a good example of usage here on SO

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜