[c#] How to create JSON string in C#

I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the JSON string and them format your response as JSON?

This question is related to c# asp.net json

The answer is


Encode Usage

Simple object to JSON Array EncodeJsObjectArray()

public class dummyObject
{
    public string fake { get; set; }
    public int id { get; set; }

    public dummyObject()
    {
        fake = "dummy";
        id = 5;
    }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append('[');
        sb.Append(id);
        sb.Append(',');
        sb.Append(JSONEncoders.EncodeJsString(fake));
        sb.Append(']');

        return sb.ToString();
    }
}

dummyObject[] dummys = new dummyObject[2];
dummys[0] = new dummyObject();
dummys[1] = new dummyObject();

dummys[0].fake = "mike";
dummys[0].id = 29;

string result = JSONEncoders.EncodeJsObjectArray(dummys);

Result: [[29,"mike"],[5,"dummy"]]

Pretty Usage

Pretty print JSON Array PrettyPrintJson() string extension method

string input = "[14,4,[14,\"data\"],[[5,\"10.186.122.15\"],[6,\"10.186.122.16\"]]]";
string result = input.PrettyPrintJson();

Results is:

[
   14,
   4,
   [
      14,
      "data"
   ],
   [
      [
         5,
         "10.186.122.15"
      ],
      [
         6,
         "10.186.122.16"
      ]
   ]
]

If you can't or don't want to use the two built-in JSON serializers (JavaScriptSerializer and DataContractJsonSerializer) you can try the JsonExSerializer library - I use it in a number of projects and works quite well.


You can also try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContracts, any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.

Basic Example

var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json); 

Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.


I've found that you don't need the serializer at all. If you return the object as a List. Let me use an example.

In our asmx we get the data using the variable we passed along

// return data
[WebMethod(CacheDuration = 180)]
public List<latlon> GetData(int id) 
{
    var data = from p in db.property 
               where p.id == id 
               select new latlon
               {
                   lat = p.lat,
                   lon = p.lon

               };
    return data.ToList();
}

public class latlon
{
    public string lat { get; set; }
    public string lon { get; set; }
}

Then using jquery we access the service, passing along that variable.

// get latlon
function getlatlon(propertyid) {
var mydata;

$.ajax({
    url: "getData.asmx/GetLatLon",
    type: "POST",
    data: "{'id': '" + propertyid + "'}",
    async: false,
    contentType: "application/json;",
    dataType: "json",
    success: function (data, textStatus, jqXHR) { //
        mydata = data;
    },
    error: function (xmlHttpRequest, textStatus, errorThrown) {
        console.log(xmlHttpRequest.responseText);
        console.log(textStatus);
        console.log(errorThrown);
    }
});
return mydata;
}

// call the function with your data
latlondata = getlatlon(id);

And we get our response.

{"d":[{"__type":"MapData+latlon","lat":"40.7031420","lon":"-80.6047970}]}

Using Newtonsoft.Json makes it really easier:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);

Documentation: Serializing and Deserializing JSON


This code snippet uses the DataContractJsonSerializer from System.Runtime.Serialization.Json in .NET 3.5.

public static string ToJson<T>(/* this */ T value, Encoding encoding)
{
    var serializer = new DataContractJsonSerializer(typeof(T));

    using (var stream = new MemoryStream())
    {
        using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
        {
            serializer.WriteObject(writer, value);
        }

        return encoding.GetString(stream.ToArray());
    }
}

Include:

using System.Text.Json;

Then serialize your object_to_serialize like this: JsonSerializer.Serialize(object_to_serialize)


If you're trying to create a web service to serve data over JSON to a web page, consider using the ASP.NET Ajax toolkit:

http://www.asp.net/learn/ajax/tutorial-05-cs.aspx

It will automatically convert your objects served over a webservice to json, and create the proxy class that you can use to connect to it.


Simlpe use of Newtonsoft.Json and Newtonsoft.Json.Linq libraries.

        //Create my object
        var my_jsondata = new
        {
            Host = @"sftp.myhost.gr",
            UserName = "my_username",
            Password = "my_password",
            SourceDir = "/export/zip/mypath/",
            FileName = "my_file.zip"
        };

        //Tranform it to Json object
        string json_data = JsonConvert.SerializeObject(my_jsondata);

        //Print the Json object
        Console.WriteLine(json_data);

        //Parse the json object
        JObject json_object = JObject.Parse(json_data);

        //Print the parsed Json object
        Console.WriteLine((string)json_object["Host"]);
        Console.WriteLine((string)json_object["UserName"]);
        Console.WriteLine((string)json_object["Password"]);
        Console.WriteLine((string)json_object["SourceDir"]);
        Console.WriteLine((string)json_object["FileName"]);

The DataContractJSONSerializer will do everything for you with the same easy as the XMLSerializer. Its trivial to use this in a web app. If you are using WCF, you can specify its use with an attribute. The DataContractSerializer family is also very fast.


If you need complex result (embedded) create your own structure:

class templateRequest
{
    public String[] registration_ids;
    public Data data;
    public class Data
    {
        public String message;
        public String tickerText;
        public String contentTitle;
        public Data(String message, String tickerText, string contentTitle)
        {
            this.message = message;
            this.tickerText = tickerText;
            this.contentTitle = contentTitle;
        }                
    };
}

and then you can obtain JSON string with calling

List<String> ids = new List<string>() { "id1", "id2" };
templateRequest request = new templeteRequest();
request.registration_ids = ids.ToArray();
request.data = new templateRequest.Data("Your message", "Your ticker", "Your content");

string json = new JavaScriptSerializer().Serialize(request);

The result will be like this:

json = "{\"registration_ids\":[\"id1\",\"id2\"],\"data\":{\"message\":\"Your message\",\"tickerText\":\"Your ticket\",\"contentTitle\":\"Your content\"}}"

Hope it helps!


This library is very good for JSON from C#

http://james.newtonking.com/pages/json-net.aspx


Take a look at http://www.codeplex.com/json/ for the json-net.aspx project. Why re-invent the wheel?


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?