12

我正在使用这种方法来形成json字符串,这工作正常。但如果它包含更多属性,我将无法处理。还有比这更好的方法吗?

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

输出是

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

5 回答 5

16

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.

于 2013-07-30T10:47:14.163 回答
8

您可以使用JSON.Net库。您可以创建要转换为 JSON 的实体类,而不是使用字符串格式化程序。

例如

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

输出:

// {
//   "Email": "james@example.com",
//   "Active": true,
//   "CreatedDate": "2013-01-20T00:00:00Z",
//   "Roles": [
//     "User",
//     "Admin"
//   ]
// }
于 2013-07-30T10:52:24.940 回答
6

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

string.Format(@"{{""longUrl"":""{0}""}}", longUrl);
于 2013-07-30T10:47:40.110 回答
2

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());
    }
}
于 2013-07-30T10:47:56.527 回答
1

然后你可以using System.Web.Script.Serialization;

 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);
于 2013-07-30T10:51:32.883 回答