简体   繁体   English

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

[英]How can I convert Serialized stream to a string?

I need to serialize and deserialize a list and write it on a JSON file to use later. 我需要序列化和反序列化列表,并将其写在JSON文件中,以备后用。

I successfully desirialize the file but failed to write after serialization. 我成功地对文件进行了反序列化,但在序列化后无法写入。 How can I do that? 我怎样才能做到这一点?

Here is the code I have written. 这是我编写的代码。

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);

DataFormat Class - DataFormat类-

[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));
    }

}

Additionally If there is any way to just add lines into an existing file without replacing all the text, please let me know. 另外,如果有任何方法可以将行添加到现有文件中而不替换所有文本,请告诉我。

See if the following code is what you need. 看看下面的代码是否是您所需要的。 I'm not so sure whether you mean you don't understand how to write to stream. 我不确定您是否表示不了解如何编写流式传输。

  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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM