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

您可以使用JavaScriptSerializer类来构建一个有用的扩展方法。

文章中的代码:

namespace ExtensionMethods
{
    public static class JSONHelper
    {
        public static string ToJSON(this object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        public static string ToJSON(this object obj, int recursionDepth)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(obj);
        }
    }
}

用法:

using ExtensionMethods;

...

List<Person> people = new List<Person>{
                   new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
                   new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
                   };


string jsonString = people.ToJSON();

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

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

希望能有所帮助!

如果你不能或不想使用两个内置的JSON序列化器(JavaScriptSerializer和DataContractJsonSerializer),你可以尝试JsonExSerializer库——我在许多项目中使用它,工作得很好。

编码使用

JSON数组的简单对象EncodeJsObjectArray()

public class dummyObject
{
    public string fake { get; set; }
    public int id { get; set; }

    public dummyObject()
    {
        fake = "dummy";
        id = 5;
    }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append('[');
        sb.Append(id);
        sb.Append(',');
        sb.Append(JSONEncoders.EncodeJsString(fake));
        sb.Append(']');

        return sb.ToString();
    }
}

dummyObject[] dummys = new dummyObject[2];
dummys[0] = new dummyObject();
dummys[1] = new dummyObject();

dummys[0].fake = "mike";
dummys[0].id = 29;

string result = JSONEncoders.EncodeJsObjectArray(dummys);

论点: [29,“迈克”[5],“笨蛋”]

漂亮的用法

Pretty print JSON数组PrettyPrintJson()字符串扩展方法

string input = "[14,4,[14,\"data\"],[[5,\"10.186.122.15\"],[6,\"10.186.122.16\"]]]";
string result = input.PrettyPrintJson();

结果是:

[
   14,
   4,
   [
      14,
      "data"
   ],
   [
      [
         5,
         "10.186.122.15"
      ],
      [
         6,
         "10.186.122.16"
      ]
   ]
]