附加JSON文件

时间:2019-07-20 04:24:43

标签: c#

我正在尝试将数据附加到现有的JSON文件中

我无法有效地摆脱[]。任何专业提示将大有帮助

谢谢

ps。那些可能会问的人,我无法始终读取和反序列化/序列化整个文件。

数据来自:

public class data
    {
        public string name { get; set; }
        public string date { get; set; }
        public int x { get; set; }
        public int y { get; set; }
    }

    static void Main(string[] args)
    {
        ...
        DateTime moment = DateTime.Now;
        List<data> _data = new List<data>();
        _data.Add(new data()
        {
            name = str[1],
            date = moment.Date.ToString("yyyy-MM-dd") + "T" + str[2],
            x = int.Parse(str[3]),
            y = int.Parse(str[8])
        });
    }

我尝试过的事情:

using (var fs = new FileStream("test.txt", 
            FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
        {
            JsonSerializer serializer = new JsonSerializer();

            using (var sw = new StreamWriter(fs))
            {
                fs.Seek(-Encoding.UTF8.GetByteCount("]"),SeekOrigin.End);                    
                sw.Write(",");
                sw.Flush();
                serializer.Serialize(sw, _data);
                sw.Write(']');
            }
        }

它输出

[{"Name":"ABC","Date":"2019-07-20T130924","X":456,"Y":-42}, 
[{"Name":"DEF","Date":"2020-01-20T130924","X":123,"Y":-12}]]

但是我希望成为这样

[{"Name":"ABC","Date":"2019-07-20T130924","X":456,"Y":-42}, 
{"Name":"DEF","Date":"2020-01-20T130924","X":123,"Y":-12}]

1 个答案:

答案 0 :(得分:-1)

它可以变得更简单

using (StreamReader sr = new StreamReader(Server.MapPath("~/path-to-file/file.txt")))
{
    string fileContents = sr.ReadToEnd();
    // get the contents, except the last character.
    fileContents = fileContents.Substring(0, fileContents.Length - 1);
    // add the new text plus bracket.
    fileContents += "new stuff here]";
    // save.
}