如何将序列化流转换为字符串?

How can I convert Serialized stream to a string?

我需要序列化和反序列化一个列表,并将其写入 JSON 文件以备后用。

文件反序列化成功,序列化后写入失败。我该怎么做?

这是我写的代码。

StorageFile savedFile = await storageFolder.GetFileAsync("SavedData.json");
string text = await FileIO.ReadTextAsync(savedFile);
var serializer = new DataContractJsonSerializer(typeof(DataFormat));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(text));
List<DataFormat> data = (List<DataFormat>)serializer.ReadObject(ms);
        if (data == null)
        {
            data = new List<DataFormat>();
        }
        data.Add(new DataFormat
        {
            firstName = fnbox.Text,
            lastName = lnbox.Text,
            country = cbox.Text
        });

MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DataFormat));
ser.WriteObject(stream, data);

数据格式Class -

[DataContract]
public class DataFormat : IEquatable<DataFormat>
{
    [DataMember]
    public string firstName{ get; set; }
    [DataMember]
    public string lastName { get; set; }
    [DataMember]
    public string country { get; set; }
    public bool Equals(DataFormat other)
    {
        if (other == null)
        {
            return false;
        }

        return (firstName.Equals(other.firstName));
    }

}

此外如果有任何方法可以将行添加到现有的 文件而不替换所有文本,请告诉我。

这里有你需要的,你可以使用 LosFormatter class - 看 https://weblog.west-wind.com/posts/2006/Oct/13/LosFormatter-for-easy-Serialization

看看下面的代码是不是你需要的。我不太确定你是不是说你不明白如何写入流。

  private async void Button_Click(object sender, RoutedEventArgs e)
    {
        Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
        Windows.Storage.StorageFile sampleFile =await storageFolder.GetFileAsync("sample.json");
        DataFormat data = new DataFormat();
        data.firstName = "Barry";
        data.lastName = "Wang";
        data.country = "China";
        Stream mystream = await sampleFile.OpenStreamForWriteAsync();          
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DataFormat));
        ser.WriteObject(mystream, data);
    }