Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSON in .Net

Tags:

c#

.net

vb.net

What libraries are available to handle JSON in .Net? I've seen this: http://james.newtonking.com/projects/json-net.aspx but would prefer a native library, if possible.

like image 513
sKIPper76 Avatar asked May 25 '26 14:05

sKIPper76


2 Answers

I have been using the JavaScriptSerializer some to expose data structures from a WCF service to Ajax calls, and it has been working out quite well.

like image 141
Fredrik Mörk Avatar answered May 27 '26 03:05

Fredrik Mörk


The JavaScriptSerializer has been marked as obsolete in .NET 3.5 and but you could use the DataContractJsonSerializer.

EDIT: See this question on SO about whether JavaScriptSerializer is actually obsolete going forward in the .NET BCL. It looks like JavaScriptSerializer is no longer obsolete in .NET 3.5 SP1 - so it's probably fine to use that. If in doubt, you can use the contract serializer from WCF, or JSON.NET (if you're willing to include 3rd party code).

Here's some wrapper code to make using DataContractJsonSerializer nicer.

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

public class JSONHelper
{
    public static string Serialize<T>(T obj)
    {
        DataContractJsonSerializer serializer = 
              new DataContractJsonSerializer(obj.GetType());
        using( MemoryStream ms = new MemoryStream() ) 
        {
            serializer.WriteObject(ms, obj);
            string retVal = Encoding.Default.GetString(ms.ToArray());
            return retVal;
        }
    }

    public static T Deserialize<T>(string json)
    {
        using( MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)) )
        {
            DataContractJsonSerializer serializer =
                  new DataContractJsonSerializer(typeof(T));
            T obj = (T)serializer.ReadObject(ms);
            ms.Close();
            return obj;
        }
    }
}

The code above is courtesy of: http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx,

I have altered it from it's original form to use best practices for object disposal (the using pattern .NET supports).

like image 27
LBushkin Avatar answered May 27 '26 03:05

LBushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!