You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不依赖序列化/第三方库实现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.
  • Line Breaks: Added newlines after:
    • The array opening bracket [.
    • Each object opening {.
    • Each key-value pair.
    • Each object closing }.
  • Fixed Quote Syntax: Corrected the original typo where \"\" was used (which would produce double quotes) to \" for valid JSON quote escaping.

Important Notes:

  1. 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.
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:22:47