user1618825
user1618825

Reputation:

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"}

Upvotes: 12

Views: 74342

Answers (6)

Vlad Setchin
Vlad Setchin

Reputation: 121

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}""
}}"';

Upvotes: 0

Simon Belanger
Simon Belanger

Reputation: 14880

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.

Upvotes: 16

vendettamit
vendettamit

Reputation: 14687

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"
//   ]
// }

Upvotes: 8

Utku
Utku

Reputation: 31

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

Upvotes: 1

Alex Filipovici
Alex Filipovici

Reputation: 32571

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

Upvotes: 2

Kent Boogaart
Kent Boogaart

Reputation: 178810

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

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

Upvotes: 5

Related Questions