39

I'm trying to serialize a local object to json but msdn documentation always seems to confuse me. I believe I am suppose to use the DataContractJsonSerializer but not completely sure, as I have seen mixed responses. I've also had someone recommend Newtonsoft.

Does anyone have any experience with this that can point me in the right direction?

7
  • 1
    there is nothing wrong with DataContract.JsonSerializer. AFAIK it is also used when WCF serializes an object into JSON Commented Nov 7, 2012 at 21:24
  • 2
    If you can use the framework tools do so instead of adding additional dependencies and overhead. Commented Nov 7, 2012 at 21:27
  • 1
    @f0x MVC4 uses Json.Net not the built-in ones. Commented Nov 7, 2012 at 21:28
  • 1
    I am using MVC4 for this specific project. Thanks for the help guys. Commented Nov 7, 2012 at 21:30
  • 1
    Funny how closed questions are often the most useful (or how the most useful are often closed??) Commented Jan 13, 2015 at 16:12

4 Answers 4

67

You could use the JavaScriptSerializer.

http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

var thing = new Thing();
var json = new JavaScriptSerializer().Serialize(thing);
Sign up to request clarification or add additional context in comments.

Comments

7

Well ServiceStack's JSON serializer is the fastest .NET JSON serializer.

And weighing at only 159kb it's also very lightweight, not too mention contains lots of useful features, e.g. .NET's fastest JSV and CSV text serializers, T.Dump() utils + more.

1 Comment

ServiceStack is excellent, however it is GPL 3.0 which can easily rule out its use for many people.
4

Unless you have some very specific json needs, stick with the framework serializer. You will find more feedback on eventual problems.

Comments

4

There are so many different json libraries in .NET, which provide for some sort of serialization. Look at the bottom of http://json.org/ to find a list of JSON libraries for C#. Whichever one is best depends on your needs. I've used json.net from Newtonsoft, although personally I have found the serializer to be very slow. If you need speed Servicestack claims to have the fastest one (here). The site also shows some performance comparisons, although I have not tried it.

Do some Googling, or simply try them out, write some tests, or just pick the framework one and introduce no extra dependencies and be done with it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.