1057

I have classes like these:

class MyDate
{
    int year, month, day;
}

class Lad
{
    string firstName;
    string lastName;
    MyDate dateOfBirth;
}

And I would like to turn a Lad object into a JSON string like this:

{
    "firstName":"Markoff",
    "lastName":"Chaney",
    "dateOfBirth":
    {
        "year":"1901",
        "month":"4",
        "day":"30"
    }
}

(Without the formatting). I found this link, but it uses a namespace that's not in .NET 4. I also heard about JSON.NET, but their site seems to be down at the moment, and I'm not keen on using external DLL files.

Are there other options besides manually creating a JSON string writer?

iliketocode
  • 6,652
  • 4
  • 41
  • 57
Hui
  • 12,039
  • 8
  • 23
  • 20
  • possible duplicate of [Generics / JSON JavaScriptSerializer C#](http://stackoverflow.com/questions/304081/generics-json-javascriptserializer-c) – Filip Ekberg Jun 01 '11 at 13:03
  • Not to mention it has no dependencies on the System.Web.Xyz namespaces... – Dave Jellison Mar 06 '13 at 18:58
  • yes. C# has a type called JavaScriptSerializer – Glenn Ferrie Jun 01 '11 at 13:02
  • 3
    Hm.. as far as I can see you should be able to use: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx Which is also in .Net 4.0 according to the MSDN page. You should be able to use the Serialize(Object obj) method: http://msdn.microsoft.com/en-us/library/bb292287.aspx Am I missing something here? Btw. you link seems to be a some code and not a link – Holger Jun 01 '11 at 13:04
  • 4
    JSON.net can be loaded [here](http://json.codeplex.com/) An other and faster (as they say - I did not test it myself) solution is [ServiceStack.Text](https://github.com/ServiceStack/ServiceStack.Text#readme) I would not recommend rolling your own JSON parser. It will likely be slower and more error prone or you have to invest lots of time. – Zebi Jun 01 '11 at 13:01

17 Answers17

1188

Since we all love one-liners

... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.

Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})

Documentation: Serializing and Deserializing JSON

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
mschmoock
  • 17,114
  • 5
  • 30
  • 32
  • 148
    Newtonsoft serializer is way faster and mor customizable then built in. Highly recommend to use it. Thanks for the answer @willsteel – Andrei Oct 02 '13 at 13:04
  • It's worth pointing out that it's not really free. See /pricing on the website. – Josef Pfleger Jun 01 '15 at 08:53
  • 9
    @JosefPfleger the pricing is for JSON.NET Schema, not JSON.NET the regular serializer, which is MIT – David Cumps Jun 03 '15 at 19:51
  • 1
    My testing showed that Newtonsoft is slower than JavaScriptSerializer class. (.NET 4.5.2) – nemke Sep 28 '15 at 11:34
  • 34
    If you read the MSDN documentation for [JavaScriptSerializer](https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx), it flat out says use JSON.net. – dsghi Nov 05 '15 at 06:10
  • 5
    @JosefPfleger Newtionsoft JSON.net is MIT licensed... you could make modifications and resell it it you wanted. Their pricing page is about commercial technical support, and some schema validator they have. – cb88 Aug 24 '16 at 15:28
  • 1
    With `JavaScriptSerializer` DateTime property was serialized as `"date": "/Date(1490648400000)/"` and was causing deserialized date to be a day back .In `Newtonsof` was `"date": "2017-03-29T00:00:00"` and solved my problem. – Stamos Mar 30 '17 at 10:09
  • ExpandoObject could be the way to go if you guys want to create a dynamic object. – Baz Guvenkaya Jul 06 '17 at 01:55
  • For everyone reading this, do note that this answer is very very old. Although Newtonsoft.Json is still very popular, and does the job, do consider using the new (built in) System.Text.Json which is mentioned in other answers – Jim Aho May 25 '21 at 15:13
964

You could use the JavaScriptSerializer class (add reference to System.Web.Extensions):

using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);

A full example:

using System;
using System.Web.Script.Serialization;

public class MyDate
{
    public int year;
    public int month;
    public int day;
}

public class Lad
{
    public string firstName;
    public string lastName;
    public MyDate dateOfBirth;
}

class Program
{
    static void Main()
    {
        var obj = new Lad
        {
            firstName = "Markoff",
            lastName = "Chaney",
            dateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };
        var json = new JavaScriptSerializer().Serialize(obj);
        Console.WriteLine(json);
    }
}
iliketocode
  • 6,652
  • 4
  • 41
  • 57
Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876
  • 112
    Please have in mind that Microsoft suggests to use JSON.net instead of this solution. I think that this answer became inappropriate. Take a look at willsteel's answer. Source: [https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx](https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx). – rzelek Feb 01 '16 at 15:12
  • 13
    @DarinDimitrov you should consider adding a hint about JSON.net. Microsoft recommends it over JavascriptSerializer: https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx You could also add a hint to https://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer(v=vs.110).aspx which is the framework included approach – Mafii Jul 06 '16 at 10:19
  • 1
    [here](http://csharp2json.azurewebsites.net/) is **online tool** to convert your `classes` to `json` format, hope helps someone. – Shaiju T Jan 25 '17 at 08:24
  • using System.Web.Script.Serialization; – Happy Bird Feb 13 '17 at 15:31
  • 9
    Why would Microsoft recommend a 3rd party solution over their own? Their wording is very odd as well: "Json.NET should be used serialization and deserialization. Provides serialization and deserialization functionality for AJAX-enabled applications." – Protector one Mar 17 '17 at 09:53
  • but this solution not return number as string... please tell me a solution same of **javascript stringify**, that it convert any key:value to string. my problem is with **number**. – Hossein Ganjyar Apr 16 '18 at 08:32
  • @rzlek Microsoft only recommended JSON.net for one specific version of the .net library (If you believe the butchered english that is). That recommendation did NOT carry over after that, and the link posted is no longer being maintained. – whiskeyfur Aug 10 '18 at 16:57
  • 2
    Just a heads up, to reference to `System.Web.Extensions`, you must have `ASP.NET AJAX 1.0` or `ASP.NET 3.5` installed on your system. Please see this https://stackoverflow.com/questions/7723489/could-not-load-file-or-assembly-system-web-extensions-version-1-0-61025-0-erro – Sisir Oct 15 '18 at 09:18
112

Use Json.Net library, you can download it from Nuget Packet Manager.

Serializing to Json String:

 var obj = new Lad
        {
            firstName = "Markoff",
            lastName = "Chaney",
            dateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };

var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

Deserializing to Object:

var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Lad>(jsonString );
Gokulan P H
  • 1,570
  • 1
  • 8
  • 10
62

Use the DataContractJsonSerializer class: MSDN1, MSDN2.

My example: HERE.

It can also safely deserialize objects from a JSON string, unlike JavaScriptSerializer. But personally I still prefer Json.NET.

Edgar
  • 4,098
  • 4
  • 38
  • 56
  • 2
    Still don't see any examples on *that page*, but here are some on [MSDN](http://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx) and [elsewhere](http://www.joe-stevens.com/2009/12/29/json-serialization-using-the-datacontractjsonserializer-and-c/) -> the last one uses extension methods to achieve one-liners. – Cristian Diaconescu Jan 17 '15 at 21:26
  • Oh, I missed the 2nd MSDN link :) – Cristian Diaconescu Jan 19 '15 at 08:48
  • 4
    It doesn't serialize plain classes. The error reported "Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute." – Michael Freidgeim Jul 14 '16 at 02:56
  • @MichaelFreidgeim That's right, you have to mark properties in the class you want to serialize with attributes. [DataContractAttribute](https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute(v=vs.110).aspx) [DataMemberAttribute](https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute(v=vs.110).aspx) – Edgar Jul 15 '16 at 06:25
  • @Edgar: this is why JavaScriptSerializer better :) – Michael Freidgeim Jul 15 '16 at 07:14
  • 1
    @MichaelFreidgeim Which is better depends on the requirements. The attributes let you configure how the property is serialized. – Edgar Jul 15 '16 at 13:49
  • DataContractJsonSerializer is very bad because it requires attributes to be set for any type (e.g. library objects). – amuliar Nov 13 '17 at 11:58
40

A new JSON serializer is available in the System.Text.Json namespace. It's included in the .NET Core 3.0 shared framework and is in a NuGet package for projects that target .NET Standard or .NET Framework or .NET Core 2.x.

Example code:

using System;
using System.Text.Json;

public class MyDate
{
    public int year { get; set; }
    public int month { get; set; }
    public int day { get; set; }
}

public class Lad
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public MyDate DateOfBirth { get; set; }
}

class Program
{
    static void Main()
    {
        var lad = new Lad
        {
            FirstName = "Markoff",
            LastName = "Chaney",
            DateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };
        var json = JsonSerializer.Serialize(lad);
        Console.WriteLine(json);
    }
}

In this example the classes to be serialized have properties rather than fields; the System.Text.Json serializer currently doesn't serialize fields.

Documentation:

tdykstra
  • 5,540
  • 2
  • 21
  • 19
31

You can achieve this by using Newtonsoft.json. Install Newtonsoft.json from NuGet. And then:

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(obj);
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Waleed Naveed
  • 1,590
  • 1
  • 16
  • 29
25

Wooou! Really better using a JSON framework :)

Here is my example using Json.NET (http://james.newtonking.com/json):

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.IO;

namespace com.blogspot.jeanjmichel.jsontest.model
{
    public class Contact
    {
        private Int64 id;
        private String name;
        List<Address> addresses;

        public Int64 Id
        {
            set { this.id = value; }
            get { return this.id; }
        }

        public String Name
        {
            set { this.name = value; }
            get { return this.name; }
        }

        public List<Address> Addresses
        {
            set { this.addresses = value; }
            get { return this.addresses; }
        }

        public String ToJSONRepresentation()
        {
            StringBuilder sb = new StringBuilder();
            JsonWriter jw = new JsonTextWriter(new StringWriter(sb));

            jw.Formatting = Formatting.Indented;
            jw.WriteStartObject();
            jw.WritePropertyName("id");
            jw.WriteValue(this.Id);
            jw.WritePropertyName("name");
            jw.WriteValue(this.Name);

            jw.WritePropertyName("addresses");
            jw.WriteStartArray();

            int i;
            i = 0;

            for (i = 0; i < addresses.Count; i++)
            {
                jw.WriteStartObject();
                jw.WritePropertyName("id");
                jw.WriteValue(addresses[i].Id);
                jw.WritePropertyName("streetAddress");
                jw.WriteValue(addresses[i].StreetAddress);
                jw.WritePropertyName("complement");
                jw.WriteValue(addresses[i].Complement);
                jw.WritePropertyName("city");
                jw.WriteValue(addresses[i].City);
                jw.WritePropertyName("province");
                jw.WriteValue(addresses[i].Province);
                jw.WritePropertyName("country");
                jw.WriteValue(addresses[i].Country);
                jw.WritePropertyName("postalCode");
                jw.WriteValue(addresses[i].PostalCode);
                jw.WriteEndObject();
            }

            jw.WriteEndArray();

            jw.WriteEndObject();

            return sb.ToString();
        }

        public Contact()
        {
        }

        public Contact(Int64 id, String personName, List<Address> addresses)
        {
            this.id = id;
            this.name = personName;
            this.addresses = addresses;
        }

        public Contact(String JSONRepresentation)
        {
            //To do
        }
    }
}

The test:

using System;
using System.Collections.Generic;
using com.blogspot.jeanjmichel.jsontest.model;

namespace com.blogspot.jeanjmichel.jsontest.main
{
    public class Program
    {
        static void Main(string[] args)
        {
            List<Address> addresses = new List<Address>();
            addresses.Add(new Address(1, "Rua Dr. Fernandes Coelho, 85", "15º andar", "São Paulo", "São Paulo", "Brazil", "05423040"));
            addresses.Add(new Address(2, "Avenida Senador Teotônio Vilela, 241", null, "São Paulo", "São Paulo", "Brazil", null));

            Contact contact = new Contact(1, "Ayrton Senna", addresses);

            Console.WriteLine(contact.ToJSONRepresentation());
            Console.ReadKey();
        }
    }
}

The result:

{
  "id": 1,
  "name": "Ayrton Senna",
  "addresses": [
    {
      "id": 1,
      "streetAddress": "Rua Dr. Fernandes Coelho, 85",
      "complement": "15º andar",
      "city": "São Paulo",
      "province": "São Paulo",
      "country": "Brazil",
      "postalCode": "05423040"
    },
    {
      "id": 2,
      "streetAddress": "Avenida Senador Teotônio Vilela, 241",
      "complement": null,
      "city": "São Paulo",
      "province": "São Paulo",
      "country": "Brazil",
      "postalCode": null
    }
  ]
}

Now I will implement the constructor method that will receives a JSON string and populates the class' fields.

Majid
  • 12,271
  • 14
  • 71
  • 107
Jean J. Michel
  • 531
  • 7
  • 13
  • 1
    Good post, this is the most current way to do it. – MatthewD May 30 '16 at 13:33
  • 1
    I guess one expects to find a unit test under "The test" section, whereas there is none. btw, I like the approach where the `Contact` object knows how to convert itself to JSON. What I don't like in this example, is that the object is not actually an object from OOP perspective, rather than just bunch of public methods and properties. – Artur Beljajev Mar 13 '21 at 16:41
10

If they are not very big, what's probably your case export it as JSON.

Also this makes it portable among all platforms.

using Newtonsoft.Json;

[TestMethod]
public void ExportJson()
{
    double[,] b = new double[,]
        {
            { 110,  120,  130,  140, 150 },
            {1110, 1120, 1130, 1140, 1150},
            {1000,    1,   5,     9, 1000},
            {1110,    2,   6,    10, 1110},
            {1220,    3,   7,    11, 1220},
            {1330,    4,   8,    12, 1330}
        };

    string jsonStr = JsonConvert.SerializeObject(b);

    Console.WriteLine(jsonStr);

    string path = "X:\\Programming\\workspaceEclipse\\PyTutorials\\src\\tensorflow_tutorials\\export.txt";

    File.WriteAllText(path, jsonStr);
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
user8426627
  • 863
  • 6
  • 17
8

If you are in an ASP.NET MVC web controller it's as simple as:

string ladAsJson = Json(Lad);

Can't believe no one has mentioned this.

micahhoover
  • 1,922
  • 6
  • 29
  • 52
5

I would vote for ServiceStack's JSON Serializer:

using ServiceStack;

string jsonString = new { FirstName = "James" }.ToJson();

It is also the fastest JSON serializer available for .NET: http://www.servicestack.net/benchmarks/

Aage
  • 4,963
  • 1
  • 26
  • 53
James
  • 2,236
  • 1
  • 23
  • 49
  • 5
    Those are very old benchmarks there. I've just test all three current versions of Newtonsoft, ServiceStack and JavaScriptSerializer and currently Newtonsoft is the fastest. Tho they all do quite fast. – Michael Logutov Oct 25 '13 at 09:22
  • 1
    ServiceStack doesn't appear to be free. – joelnet Dec 19 '13 at 00:25
  • 1
    @joelnet this is now the case, but was free when answering the question. However it is free for small sites, and I am still using it even though it is paid, it is a superb framework. – James Dec 19 '13 at 10:21
  • Some benchmarks here, though there's non for the serialization on its own: http://docs.servicestack.net/real-world-performance – JohnLBevan Dec 13 '18 at 09:39
  • 2
    @joelnet Seems to be free now. Don't know when they changed it. – Aage Jun 22 '20 at 11:48
4

Use these tools for generating a C# class, and then use this code to serialize your object:

 var json = new JavaScriptSerializer().Serialize(obj);
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Artem Polishchuk
  • 445
  • 4
  • 16
3

Use the below code for converting XML to JSON.

var json = new JavaScriptSerializer().Serialize(obj);
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Hithesh
  • 447
  • 3
  • 9
3

It is as easy as this (it works for dynamic objects as well (type object)):

string json = new
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(MYOBJECT);
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
MarzSocks
  • 3,733
  • 2
  • 19
  • 32
1

Another solution using System.Text.Json (.NET Core 3.0+, .NET 5) where an object is self-sufficient and doesn't expose all possible fields:

A passing test:

using NUnit.Framework;

namespace Intech.UnitTests
{
    public class UserTests
    {
        [Test]
        public void ConvertsItselfToJson()
        {
            var userName = "John";
            var user = new User(userName);

            var actual = user.ToJson();

            Assert.AreEqual($"{{\"Name\":\"{userName}\"}}", actual);
        }
    }
}

An implementation:

using System.Text.Json;
using System.Collections.Generic;

namespace Intech
{
    public class User
    {
        private readonly string Name;

        public User(string name)
        {
            this.Name = name;
        }

        public string ToJson()
        {
            var params = new Dictionary<string, string>{{"Name", Name}};
            return JsonSerializer.Serialize(params);
        }
    }
}
Artur Beljajev
  • 4,424
  • 2
  • 25
  • 23
1

Here is another solution using Cinchoo ETL - an open source library

public class MyDate
{
    public int year { get; set; }
    public int month { get; set; }
    public int day { get; set; }
}

public class Lad
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public MyDate dateOfBirth { get; set; }
}

static void ToJsonString()
{
    var obj = new Lad
    {
        firstName = "Tom",
        lastName = "Smith",
        dateOfBirth = new MyDate
        {
            year = 1901,
            month = 4,
            day = 30
        }
    };
    var json = ChoJSONWriter.Serialize<Lad>(obj);

    Console.WriteLine(json);
}

Output:

{
  "firstName": "Tom",
  "lastName": "Smith",
  "dateOfBirth": {
    "year": 1901,
    "month": 4,
    "day": 30
  }
}

Disclaimer: I'm the author of this library.

Cinchoo
  • 5,202
  • 2
  • 14
  • 30
0

Serializer

 public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
        var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite, new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
        });
        using (var writer = new StreamWriter(filePath, append))
        {
            writer.Write(contentsToWriteToFile);
        }
}

Object

namespace MyConfig
{
    public class AppConfigurationSettings
    {
        public AppConfigurationSettings()
        {
            /* initialize the object if you want to output a new document
             * for use as a template or default settings possibly when 
             * an app is started.
             */
            if (AppSettings == null) { AppSettings=new AppSettings();}
        }

        public AppSettings AppSettings { get; set; }
    }

    public class AppSettings
    {
        public bool DebugMode { get; set; } = false;
    }
}

Implementation

var jsonObject = new AppConfigurationSettings();
WriteToJsonFile<AppConfigurationSettings>(file.FullName, jsonObject);

Output

{
  "AppSettings": {
    "DebugMode": false
  }
}
dynamiclynk
  • 2,035
  • 23
  • 29
0

In your Lad model class, add an override to the ToString() method that returns a JSON string version of your Lad object.
Note: you will need to import System.Text.Json;

using System.Text.Json;

class MyDate
{
    int year, month, day;
}

class Lad
{
    public string firstName { get; set; };
    public string lastName { get; set; };
    public MyDate dateOfBirth { get; set; };
    public override string ToString() => JsonSerializer.Serialize<Lad>(this);
}
Mimina
  • 1,126
  • 2
  • 13
  • 13