我只是使用XmlWriter创建了一些XML,以便在HTTP响应中发回。如何创建JSON字符串?我猜你会使用stringbuilder来构建JSON字符串,然后将响应格式化为JSON?


当前回答

这个库非常适合用于c#中的JSON

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

其他回答

这个代码片段使用了。net 3.5中System.Runtime.Serialization.Json中的DataContractJsonSerializer。

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

如果你需要复杂的结果(嵌入),创建你自己的结构:

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

然后通过调用获取JSON字符串

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

结果是这样的:

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

希望能有所帮助!

简单使用Newtonsoft。Json和Newtonsoft.Json.Linq库。

        //Create my object
        var myData = 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 jsonData = JsonConvert.SerializeObject(myData);

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

        //Parse the json object
        JObject jsonObject = JObject.Parse(jsonData);

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

看看http://www.codeplex.com/json/上的json-net。aspx项目。为什么要重新发明轮子?

使用Newtonsoft。Json让它变得更简单:

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

文档:序列化和反序列化JSON