我正在使用JavaScriptSerializer將對象序列化爲JSON格式的文件。但結果文件沒有可讀格式。我如何允許格式化以獲得可讀文件?如何在JSON序列化時使用JavaScriptSerializer設置格式?
回答
似乎沒有用於格式化JSON-serializer輸出的內置工具。
我想這種情況發生的原因是最小化我們通過網絡發送的數據。
您確定您需要代碼中的格式化數據嗎?或者你想在調試過程中分析JSON?
有很多提供此類功能的在線服務:1,2。 或獨立應用程序:JSON viewer。
但是,如果您需要格式化應用程序內部,您可以自己編寫appropriate code。
你可以使用JSON.NET串行器,它支持JSON格式
string body = JsonConvert.SerializeObject(message, Formatting.Indented);
勇可以通過下載的NuGet this package。
這裏是我的解決方案,不需要使用JSON.NET,並且比Alex Zhevzhik鏈接的代碼更簡單。
using System.Web.Script.Serialization;
// add a reference to System.Web.Extensions
public void WriteToFile(string path)
{
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(this);
string json_pretty = JSON_PrettyPrinter.Process(json);
File.WriteAllText(path, json_pretty);
}
,這裏是格式化
class JSON_PrettyPrinter
{
public static string Process(string inputText)
{
bool escaped = false;
bool inquotes = false;
int column = 0;
int indentation = 0;
Stack<int> indentations = new Stack<int>();
int TABBING = 8;
StringBuilder sb = new StringBuilder();
foreach (char x in inputText)
{
sb.Append(x);
column++;
if (escaped)
{
escaped = false;
}
else
{
if (x == '\\')
{
escaped = true;
}
else if (x == '\"')
{
inquotes = !inquotes;
}
else if (!inquotes)
{
if (x == ',')
{
// if we see a comma, go to next line, and indent to the same depth
sb.Append("\r\n");
column = 0;
for (int i = 0; i < indentation; i++)
{
sb.Append(" ");
column++;
}
} else if (x == '[' || x== '{') {
// if we open a bracket or brace, indent further (push on stack)
indentations.Push(indentation);
indentation = column;
}
else if (x == ']' || x == '}')
{
// if we close a bracket or brace, undo one level of indent (pop)
indentation = indentations.Pop();
}
else if (x == ':')
{
// if we see a colon, add spaces until we get to the next
// tab stop, but without using tab characters!
while ((column % TABBING) != 0)
{
sb.Append(' ');
column++;
}
}
}
}
}
return sb.ToString();
}
}
爲什麼使用'IDisposable'?爲什麼不只是讓'Process'成爲一種靜態方法? – tenfour 2013-05-21 14:14:40
@tenfour - 你絕對正確。這個代碼片段來自一個更大的塊,它被簡化爲stackoverflow ...我將進一步簡化它。 – 2013-05-21 18:01:45
這不是每個人的解決方案!如果您的項目是.NET 4,或者您的項目不是Web名稱,則會導致頁面圖像(或格式)衝突!注意你正在使用System.Web.Extensions(需要.NET4.5!)來引入System.Web.Script.Serialization!對於具體的解決方案,您應該使用NuGet獲取Newtonsoft並使用JsonConvert.SerializeObject – 2016-01-27 15:50:21
我也希望能有JSON格式不依靠第三方組件。馬克拉卡塔的解決方案運行良好(感謝馬克),但我想括號和標籤像亞歷克斯Zhevzhik的鏈接。因此,這裏是馬克的代碼微調的版本,這樣工作,如果任何人希望它:
/// <summary>
/// Adds indentation and line breaks to output of JavaScriptSerializer
/// </summary>
public static string FormatOutput(string jsonString)
{
var stringBuilder = new StringBuilder();
bool escaping = false;
bool inQuotes = false;
int indentation = 0;
foreach (char character in jsonString)
{
if (escaping)
{
escaping = false;
stringBuilder.Append(character);
}
else
{
if (character == '\\')
{
escaping = true;
stringBuilder.Append(character);
}
else if (character == '\"')
{
inQuotes = !inQuotes;
stringBuilder.Append(character);
}
else if (!inQuotes)
{
if (character == ',')
{
stringBuilder.Append(character);
stringBuilder.Append("\r\n");
stringBuilder.Append('\t', indentation);
}
else if (character == '[' || character == '{')
{
stringBuilder.Append(character);
stringBuilder.Append("\r\n");
stringBuilder.Append('\t', ++indentation);
}
else if (character == ']' || character == '}')
{
stringBuilder.Append("\r\n");
stringBuilder.Append('\t', --indentation);
stringBuilder.Append(character);
}
else if (character == ':')
{
stringBuilder.Append(character);
stringBuilder.Append('\t');
}
else
{
stringBuilder.Append(character);
}
}
else
{
stringBuilder.Append(character);
}
}
}
return stringBuilder.ToString();
}
- 1. 使用JavaScriptSerializer C反序列化JSON#
- 2. 使用JavaScriptSerializer反序列化JSON文件()
- 3. MVC JavaScriptSerializer反序列化JSON
- 4. 如何使用JavascriptSerializer反序列化C#中的json字符串
- 5. 如何使用JavaScriptSerializer對元組反序列化JSON
- 6. 使用JSON JavaScriptSerializer進行序列化或反序列化時出錯。
- 7. 使用JSON JavaScriptSerializer進行序列化或反序列化時出錯
- 8. 如何在使用JSON JavaScriptSerializer進行序列化或反序列化時捕獲錯誤
- 9. C#JavaScriptSerializer JSON數組反序列化
- 10. 在C#中使用JSON.NET或JavaScriptSerializer反序列化JSON對象
- 11. 用Newtonsoft Json.Net替換WCF內置JavascriptSerializer json序列化器
- 12. 使用JavaScriptSerializer反序列化JSON字典列表
- 13. 從JavaScriptSerializer輸出json格式
- 14. 使用JavaScriptSerializer序列化字典
- 15. 使用泛型與JavaScriptSerializer反序列化
- 16. 使用JavaScriptSerializer反序列化JSON片段ASP.NET
- 17. 使用JavaScriptSerializer序列化爲JSON的麻煩
- 18. VB.Net Json序列化格式
- 19. Json序列化格式
- 20. JSON序列化格式
- 21. 我該如何才能JavaScriptSerializer反序列化在運行時定義的JSON
- 22. 用Json和JavaScriptSerializer反序列化JSON結果
- 23. JavaScriptSerializer。如何從JSON反序列化字符串數組?
- 24. 如何爲Jackson JSON設置一個格式化程序?
- 25. 在c#中使用JavaScriptSerializer進行序列化時得到錯誤
- 26. 如何格式化設置
- 27. 在初始化時設置日期格式化程序(例如)?
- 28. JavaScriptSerializer上反序列化
- 29. 當使用C#/ JavaScriptSerializer反序列化json時,「值不能爲空」錯誤
- 30. 錯誤:使用Python將TSV文件轉換爲JSON格式時設置不是JSON可序列化
你甚至可以設置所需的格式設置JsonConvert.SerializeObject(消息,Newtonsoft.Json.Formatting.Indented, 新JsonSerializerSettings {ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()}); – 2013-06-03 18:27:56