Google Code Prettify

產生JSON字串的幾種方式整理(1)

這邊就以Google API裡有段JSON字串當作練習怎麼產生:
image

以下整理幾種我見過的方式(個人推薦的放在最後^_^)
1. 字串拼接
最麻煩的方式,可讀性也差,若遇到Boolean型別的變數要記得轉小寫

01protected void Page_Load(object sender, EventArgs e)
02    {
03        if (!IsPostBack)//Get Method
04        {
05            //準備資料
06            string collapse_key = "score_update";
07            int time_to_live = 108;
08            bool delay_while_idle = true;
09            string score = "4x8";
10            string time = "15:16.2342";
11            List<string> registration_ids = new List<string>() { "4","8","15","16","23","42"};
12 
13 
14            //開始拼接字串
15            StringBuilder sb = new StringBuilder();
16            sb.AppendLine("{");
17            sb.AppendLine("\"collapse_key\":\""+collapse_key+"\",");
18            sb.AppendLine("\"time_to_live\":"+time_to_live+",");
19            sb.AppendLine("\"delay_while_idle\":"+delay_while_idle.ToString().ToLower()+",");
20            sb.AppendLine("\"data\":{");
21            sb.AppendLine("\"score\":\""+score+"\",");
22            sb.AppendLine("\"time\":\""+time+"\"");
23            sb.AppendLine("},");
24            sb.AppendLine("\"registration_ids\":[");
25            foreach (string item in registration_ids)
26            {
27                sb.Append("\""+item+"\",");
28            }
29            sb = new StringBuilder(sb.ToString().TrimEnd(','));//移除最後一個「,」字元
30            sb.AppendLine("]");
31            sb.AppendLine("}");
32 
33            //輸出結果
34            Response.Write(sb.ToString());
35        }
36    }
↑所以很多人會尋找第三方套件來處理吧
以下便介紹Json.net,因為威力太強大了~
image

有了Json.net後就可以使用Json.net的函數產生JSON字串
2. 使用JsonTextWriter
用法很像XmlTextWriter,寫起來有點囉嗦,平常工作我不會用這個
01protected void Page_Load(object sender, EventArgs e)
02    {
03        if (!IsPostBack)//Get Method
04        {
05            //準備資料
06            string collapse_key = "score_update";
07            int time_to_live = 108;
08            bool delay_while_idle = true;
09            string score = "4x8";
10            string time = "15:16.2342";
11            List<string> registration_ids = new List<string>() { "4","8","15","16","23","42"};
12 
13              
14            //要輸出的變數
15            StringWriter sw = new StringWriter();
16            //建立JsonTextWriter
17            JsonTextWriter writer = new JsonTextWriter(sw);
18            writer.WriteStartObject();
19            writer.WritePropertyName("collapse_key"); writer.WriteValue(collapse_key);
20            writer.WritePropertyName("time_to_live"); writer.WriteValue(time_to_live);
21            writer.WritePropertyName("delay_while_idle"); writer.WriteValue(delay_while_idle);
22            writer.WritePropertyName("data");
23            writer.WriteStartObject();
24            writer.WritePropertyName("score"); writer.WriteValue(score);
25            writer.WritePropertyName("time"); writer.WriteValue(time);
26            writer.WriteEndObject();
27            writer.WritePropertyName("registration_ids");
28            writer.WriteStartArray();
29            foreach (string item in registration_ids)
30            {
31                writer.WriteValue(item);
32            }
33            writer.WriteEndArray();
34            writer.WriteEndObject();
35  
36            //輸出結果
37            Response.Write(sw.ToString());
38        }
39    }
3. 使用JObject匿名物件
比起JsonTextWriter簡化了許多,不過大概是每個Property和值都要再寫一次建構子名稱,我覺得還是有點麻煩
01protected void Page_Load(object sender, EventArgs e)
02    {
03        if (!IsPostBack)//Get Method
04        {
05            //準備資料
06            string collapse_key = "score_update";
07            int time_to_live = 108;
08            bool delay_while_idle = true;
09            string score = "4x8";
10            string time = "15:16.2342";
11            List<string> registration_ids = new List<string>() { "4","8","15","16","23","42"};
12 
13            //JObject匿名物件
14            JObject obj = new JObject(
15                 new JProperty("collapse_key",collapse_key),
16                 new JProperty("time_to_live",time_to_live),
17                 new JProperty("delay_while_idle",delay_while_idle),
18                 new JProperty("data",
19                     new JObject(
20                         new JProperty("score",score),
21                         new JProperty("time",time))),
22                new JProperty("registration_ids",registration_ids)
23                );
24  
25            //序列化為JSON字串並輸出結果
26            Response.Write(JsonConvert.SerializeObject(obj,Formatting.Indented));
27        }
28    }

那有沒有寫起來直覺,程式碼又短少的方式呢?

請看以下兩個