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


当前回答

简单使用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项目。为什么要重新发明轮子?

如果您试图创建一个web服务,通过JSON向web页面提供数据,请考虑使用ASP。. NET Ajax工具包:

http://www.asp.net/learn/ajax/tutorial-05-cs.aspx

它会自动将你通过webservice服务的对象转换为json,并创建你可以用来连接到它的代理类。

简单使用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"]);

使用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

如果你想避免创建一个类和创建JSON,那么创建一个动态对象和序列化对象。

            dynamic data = new ExpandoObject();
            data.name = "kushal";
            data.isActive = true;

            // convert to JSON
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);

读取JSON并像这样反序列化:

            // convert back to Object
            dynamic output = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

            // read a particular value:
            output.name.Value

ExpandoObject来自System。动态名称空间。