使用DataContractJsonSerializer将元素追加到文件中的JSON数组

时间:2018-08-11 14:06:46

标签: c# json serialization

我正在尝试使用标准C#库处理JSON。我想从程序中保存一些数据以备将来使用。我决定将它们保存为JSON格式。我知道每次将新数组添加到文件中。如何确保将新元素添加到旧数组中呢?我不明白需要解决什么。

以下是序列化的示例:

private static void writeDeviceInfoInLog(string ipNum, string portNum, string deviceNum)
{
    DeviceTCP device1 = new DeviceTCP(ipNum, portNum, deviceNum);
    DeviceTCP device2 = new DeviceTCP(ipNum, portNum, deviceNum);
    DeviceTCP[] devices = new DeviceTCP[] { device1, device2 };
    DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(DeviceTCP[]));

    using (FileStream fs = new FileStream("0.json", FileMode.Append))
    {
        jsonFormatter.WriteObject(fs, devices);
    }
}

这是输出文件:

[{
    "IpDevice":"1","NumberDevice":"3","PortDevice":"2"
},{
    "IpDevice":"1","NumberDevice":"3","PortDevice":"2"
}]
[{
    "IpDevice":"1","NumberDevice":"3","PortDevice":"2"
},{
    "IpDevice":"1","NumberDevice":"3","PortDevice":"2"
}]

1 个答案:

答案 0 :(得分:1)

您必须先从文件中读取旧数组,然后用新数组覆盖它。例如(如果您确定文件已经存在并且包含有效的JSON):

DeviceTCP[] oldArray;
using (var fs = new FileStream("0.json", FileMode.Open))
{
    oldArray = (DeviceTCP[])jsonFormatter.ReadObject(fs);
}

using (var fs = new FileStream("0.json", FileMode.OpenOrCreate))
{
    jsonFormatter.WriteObject(fs, oldArray.Concat(devices).ToArray());
}

但是,这可能不是最有效的方法,尤其是在您必须经常执行此操作时。在这种情况下,您可以考虑使用内存中的数组,完成后只写入一次文件。