'Forming Json Format String

I am using this method to form json string and this is working fine. But i can't handle this if it contains more properties. Is there any other better method than this?

string.Format("{0}{1}longUrl{1}:{1}{2}{1}{3}", "{", "\"", longUrl,"}");

The output is

{"longUrl":"http://api.themoviedb.org/3/person/12835?api_key=2c50a994de5291887a4e062edd229a72"}


Solution 1:[1]

Well, a "better" way of doing this would be to use a Json library. If this is in the context of an Asp.Net website (in the latter versions), there is the Json.Net library that is automatically referenced. If not, you can use Nuget to add a reference to your project or manually add it, whichever your prefer. You could then do:

JsonConvert.SerializeObject(new { longUrl = longUrl });

Note that you can also just use new { longUrl } and the property name will be the same as your variable name.

Solution 2:[2]

You can use JSON.Net library. You can create an entity class which you want to covert to JSON rather than using string formatter.

for e.g.

    public class Account
    {
      public string Email { get; set; }
      public bool Active { get; set; }
      public DateTime CreatedDate { get; set; }
      public IList<string> Roles { get; set; } 
    }

Account account = new Account
  {
    Email = "[email protected]",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    Roles = new List<string>
      {
        "User",
        "Admin"
      }
  };

string json = JsonConvert.SerializeObject(account, Formatting.Indented);

Console.WriteLine(json);

output:

// {
//   "Email": "[email protected]",
//   "Active": true,
//   "CreatedDate": "2013-01-20T00:00:00Z",
//   "Roles": [
//     "User",
//     "Admin"
//   ]
// }

Solution 3:[3]

You could just use a JSON serializer such as JSON.NET. Failing that, you can simplify somewhat:

string.Format(@"{{""longUrl"":""{0}""}}", longUrl);

Solution 4:[4]

You may use Newtonsoft.Json:

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

class Program
{
    static void Main(string[] args)
    {
        var d = new
        {
            longUrl = "http://api.themoviedb.org/3/person/12835?api_key=2c50a994de5291887a4e062edd229a72",
            someOtherProeprty = 1
        };
        var s = new JsonSerializer();
        var sb = new StringBuilder();
        using (var w = new StringWriter(sb))
        {
            s.Serialize(w, d);
        }
        Console.WriteLine(sb.ToString());
    }
}

Solution 5:[5]

you can using System.Web.Script.Serialization; then do

 var dict = new Dictionary<string, string>
            {
                {"longUrl","http://api.themoviedb.org/3/person/12835?api_key=2c50a994de5291887a4e062edd229a72"},
                {"anotherUrl", "another Url"}
            };

var serializer = new JavaScriptSerializer();
serializer.Serialize(dict);

Solution 6:[6]

As an example to create the following JSON string

{
    "userId" : "121211-121112",
    "accountId": "xhd1121-kdkdj11"
}

use the following string interpolation and formating.

var jsonString = $@"{{
    "userId"": ""{user.Id},""
    ""accountId"": ""{account.Id}""
}}"';

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 vendettamit
Solution 3 Kent Boogaart
Solution 4 Alex Filipovici
Solution 5 Utku
Solution 6 Vlad Setchin