打印到文件时,在JSON数组中的每个对象之后添加新行

时间:2018-12-22 03:50:25

标签: json json.net

使用Git合并大型JSON文件时遇到问题。 Git似乎无法正确区分大型JSON文件。 This solution在JSON对象的每个属性之间添加额外的换行符似乎可以解决合并冲突。

问题是我的JSON文件很大,并且生成时没有换行符。我也无法控制它的生成方式。这是一个示例:

"notes":[
           {
                "__type__": "Note", 
                "data": "", 
                "fields": [
                    "Define virologic suppression in HIV", 
                    "HIV RNA level below limit of assay detection (<20copies/mL", 
                    "", 
                    ""
                ], 
                "flags": 0, 
                "guid": "B4VR%D9qb2", 
                "note_model_uuid": "0aecb5c4-d637-11e7-8e91-408d5c5c9416", 
                "tags": [
                    "InfectiousDiseases"
                ]
            }, 
            {
                "__type__": "Note", 
                "data": "", 
                "fields": [
                    "Define incomplete virological response in HIV", 
                    "Inability to achieve virologic suppression after 24 weeks of therapy (viral load >200 on 2 consecutive samples)", 
                    "", 
                    ""
                ], 
                "flags": 0, 
                "guid": "N{WL%;*sKr", 
                "note_model_uuid": "0aecb5c4-d637-11e7-8e91-408d5c5c9416", 
                "tags": [
                    "InfectiousDiseases"
                ]
            }
]

我正在尝试编写脚本以使用JSON.net添加其他换行符。这是我到目前为止的内容:

    static void Main(string[] args)
    {
        using (StreamReader file = File.OpenText(@"fracp-anki.json"))
        using (var reader = new JsonTextReader(file))
        {
            JObject deck = (JObject)JToken.ReadFrom(reader);
            var notes = (JArray)deck["notes"];
            string paddedNotes = writePaddedNotes(notes);
            Console.WriteLine(paddedNotes);
        }

    }

    public static string writePaddedNotes(JArray notes)
    {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);

        using (JsonWriter writer = new JsonTextWriter(sw))
        {
            foreach (var note in notes.Children<JObject>())
            {
                //what goes here?
            }
        }
        return sb.ToString();
    }

如何将数组中每个对象的属性写入文件,并在它们之间添加换行符?

1 个答案:

答案 0 :(得分:2)

您可以通过以下方法解决此问题:子类JsonTextWriter并重写WriteValueDelimiter方法,以便它在定界符之后写一个额外的换行符,如下所示:

class DoubleSpacedValuesJsonWriter : JsonTextWriter
{
    public DoubleSpacedValuesJsonWriter(TextWriter textWriter) : base(textWriter)
    {
        Formatting = Formatting.Indented;
    }

    protected override void WriteValueDelimiter()
    {
        base.WriteValueDelimiter();
        base.WriteWhitespace(Environment.NewLine);
    }
}

然后,您可以制作一个简短的助手方法来重新格式化JSON文件,如下所示:

public static void ReformatJsonFile(string filename)
{
    string tempFile = filename + ".tmp";

    using (StreamReader sr = new StreamReader(filename))
    using (JsonReader reader = new JsonTextReader(sr))
    using (StreamWriter sw = new StreamWriter(tempFile))
    using (JsonWriter writer = new DoubleSpacedValuesJsonWriter(sw))
    {
        writer.WriteToken(reader);
    }

    File.Delete(filename);
    File.Move(tempFile, filename);
}

这是一个有效的演示(使用控制台而不是文件):https://dotnetfiddle.net/5ZVom7

如果事实证明您还需要在开括号{}和/或括号[]之后需要其他换行符,则可以覆盖WriteStartObjectWriteEndObjectWriteStartArrayWriteEndArray方法。