Question

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"}
Was it helpful?

Solution

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.

OTHER TIPS

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 = "james@example.com",
    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": "james@example.com",
//   "Active": true,
//   "CreatedDate": "2013-01-20T00:00:00Z",
//   "Roles": [
//     "User",
//     "Admin"
//   ]
// }

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

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

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());
    }
}

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);

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}""
}}"';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top