1

I need to serialize and deserialize a list and write it on a JSON file to use later.

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 -

[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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Mahmudul Hasan
  • 798
  • 11
  • 35
  • Why not write directly to the file, as shown in the accepted answer to [Using DataContractJsonSerializer to create a Non XML Json file](https://stackoverflow.com/q/31130829)? – dbc Feb 03 '19 at 13:36
  • What do you mean by saying "add lines"? Add a new data member or add a json object? And what's the error message you get? – Barry Wang Feb 04 '19 at 07:51
  • I mean a new JSON object. And I didn't get any error cause I don't know how to write on a JSON file. That is the answer I need "How to write on a JSON file after serialization". Thanks. @BarryWang-MSFT – Mahmudul Hasan Feb 04 '19 at 08:41

2 Answers2

0

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);
    }
Barry Wang
  • 1,459
  • 1
  • 8
  • 12
  • Another short question, I need to convert data to a list after reading from an existing JSON file. How can do that? – Mahmudul Hasan Feb 07 '19 at 07:07
  • [Jsonarray](https://learn.microsoft.com/en-us/uwp/api/windows.data.json.jsonarray) and Jsonobject can help you parse the string you get from your JSON file. You can then use a loop to read them to your list. – Barry Wang Feb 14 '19 at 05:09
-1

Here what you need, you can use LosFormatter class - see https://weblog.west-wind.com/posts/2006/Oct/13/LosFormatter-for-easy-Serialization

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108