不依赖序列化/第三方库实现JSON文件格式化写入的技术问询
Solution: Manual JSON Formatting Without Libraries
To get properly formatted JSON output without using serialization tools or third-party libraries, we need to add intentional line breaks and indentation as we build the string. Here's the adjusted code that produces standard pretty-printed JSON:
public void convertToJSONsyntax(string[] data, string[] dataFields) { string[] splitData = new string[150]; // Start with root object and array opening, add newline for readability var JSONSyntaxString = "{\"DataFile1\":[\n"; for (int i = 0; i < data.Length; i++) { // Indent array items once, open object JSONSyntaxString += " {"; JSONSyntaxString += "\n"; splitData = data[i].Split('|'); for (int j = 0; j < dataFields.Length; j++) { // Indent key-value pairs twice JSONSyntaxString += " \"" + dataFields[j] + "\":\"" + splitData[j] + "\""; // Add comma if not last field, then newline if (j != dataFields.Length - 1) { JSONSyntaxString += ","; } JSONSyntaxString += "\n"; } // Close object with indent, add comma if not last item JSONSyntaxString += " }"; if (i != data.Length - 1) { JSONSyntaxString += ","; } JSONSyntaxString += "\n"; } // Close array and root object JSONSyntaxString += "]}"; File.WriteAllText("C:\\OutputData.json", JSONSyntaxString); }
Key Changes Explained:
- Indentation: We use 2 spaces per indent level (adjustable to 4 if preferred):
- Array items (
{ ... }) are indented once from the root. - Key-value pairs inside each object are indented twice.
- Array items (
- Line Breaks: Added newlines after:
- The array opening bracket
[. - Each object opening
{. - Each key-value pair.
- Each object closing
}.
- The array opening bracket
- Fixed Quote Syntax: Corrected the original typo where
\"\"was used (which would produce double quotes) to\"for valid JSON quote escaping.
Important Notes:
- Escaping Special Characters: This code assumes your data values don't contain double quotes or backslashes. If they do, you'll need to add a helper method to escape these characters (e.g., replace
"with\"and\with\\) to keep the JSON valid. - Indentation Preference: If you prefer 4 spaces instead of 2, just replace
" "with" "for array items and" "with" "for key-value pairs.
This will produce JSON that matches standard formatting, making it easy to read and validate.
内容的提问来源于stack exchange,提问作者Sidarth
相关产品推荐
相关产品推荐

