Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Json serializer do I want? [closed]

I started up a new MVC 5 Web API project, and I want to manually encode an object as JSON to save to a database. However, it seems that there are at least four different JSON-like serializer classes already available in my project:

  • System.Runtime.Serialization.Json.DataContractJsonSerializer
  • System.Web.Helpers.Json
  • Newtonsoft.Json.JsonConvert
  • Newtonsoft.Json.JsonSerializer

I sort-of understand why these four are conceptually different: one's from WCF, two are from Newtonsoft; two are quick-and-dirty converts and two are configurable serializers, etc.

What I can't figure out is, does it really matter which one I should use. Are there any functional differences between these 4 options? Will there be interoperability problems if I use one class to serialize and a different one to deserialize in another application?

like image 544
Michael Edenfield Avatar asked Nov 13 '14 16:11

Michael Edenfield


1 Answers

The Newtonsoft serializer is faster than the legacy DataContractJsonSerializer which is why it's generally included with recent versions of MVC. The two Newtonsoft types you refer to aren't both serializers though - I believe that JsonConvert is just a utility type that uses the JsonSerializer internally.

So in answer to your question the simplest (and one of the) fastest ways to serialize/deserialize json is like this:

// Serialize
YourType instance = new YourType();
string json = JsonConvert.SerializeObject(instance);

// Deserialize
string json = "json_string";
YourType instance = JsonConvert.DeserializeObject<YourType>(json);
like image 190
Will Appleby Avatar answered Oct 04 '22 14:10

Will Appleby