C# 小技巧 去除 Json 格式, 去除全部換行和空白

無意間看到之前的程式碼,這是一個當時覺得很新奇的用法,今天把它寫成文章記錄一下

Json 去除所有換行和空白

本次會使用到 Newtonsoft.Json 套件,需要先從 NuGet 安裝
    
Install-Package Newtonsoft.Json -Version 13.0.1
    

用法很簡單,就只是在 ToString 的時候加入 Formatting.None
    
    string json = jObject.ToString(Formatting.None);
    

恩,對,就這樣...

完整範例

(因為在 .NET Core 6 的 Console Application 所以可以這麼短,不用 public static void...)
    
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

string jsonString = @"{
    ""name"": ""Ruyut"",
    ""age"": 100,
    ""website"": ""http://ruyut.com"",
    ""phoneNumbers"": [
        {
            ""type"": ""home"",
            ""number"": ""123-456-7890""
        },
        {
            ""type"": ""fax"",
            ""number"": ""0987-6543-2109""
        }
    ]
}";

Console.WriteLine($"Original Json: {jsonString}");
JObject jObject = JObject.Parse(jsonString);
string json = jObject.ToString(Formatting.None);

Console.WriteLine($"New Json: {json}");
    

範例輸出:
原始 Json:
    

Console.WriteLine($"Original Json: {jsonString}");
'JSON: {
'    "name": "Ruyut",
'    "age": 100,
'    "website": "http://ruyut.com",
'    "phoneNumbers": [
'        {
'            "type": "home",
'            "number": "123-456-7890"
'        },
'        {
'            "type": "fax",
'            "number": "0987-6543-2109"
'        }
'    ]
'}


去除換行與空白後的 Json:
    
Console.WriteLine($"New Json: {json}");
'JSON: {"name":"Ruyut","age":100,"website":"http://ruyut.com","phoneNumbers":[{"type":"home","number":"123-456-7890"},{"type":"fax","number":"0987-6543-2109"}]}


留言