0

I want to save the data to the JSON file.

Using many examples on the internet, I tried to do it, but it still does not work.

[DataContract]
[KnownType(typeof(PressureSensor))]
[KnownType(typeof(TemperatureAndHumiditySensor))]
[KnownType(typeof(HumidityAndPressureSensor))]
class WeatherStation
{
    [DataMember]
    private List<Sensor> sensors = new List<Sensor>();

    [DataMember]
    public double period;

    private void SerialzieToJson()
    {
        DataContractJsonSerializer data = new DataContractJsonSerializer(typeof(WeatherStation));
        MemoryStream memory = new MemoryStream();
        data.WriteObject(memory, this);
        memory.Position = 0;

        using (FileStream stream = new FileStream(@"C:\Users\Adżi\Desktop\files\file.json", FileMode.Open))
        {
            memory.CopyTo(stream);
            stream.Flush();
        }

        memory.Position = 0;
        StreamReader streamReader = new StreamReader(memory);
        Console.WriteLine("JSON: " + streamReader.ReadToEnd());
        streamReader.Close();
        memory.Close(); 
    }
}

What am I doing wrong? Why is nothing saved in the file?

dbc
  • 104,963
  • 20
  • 228
  • 340
  • 1
    Could you explain what doesn't work ? Does your code throws an exception, does it generates an empty file ? – B. Lec May 21 '19 at 10:01
  • The file to which I want to save the data exists. The code does not throw an exception. It looks like it works well, but the file is empty. – Adrianna Tyszkiewicz May 21 '19 at 10:04
  • Try adding try..catch.. within SerialzieToJson method. And try to change the directory to C:\Temp for example to test it out. – hdz200 May 21 '19 at 10:16
  • @AviMeltser No exception is caught. – Adrianna Tyszkiewicz May 21 '19 at 10:23
  • @Lion200 Nothing has changed. – Adrianna Tyszkiewicz May 21 '19 at 10:23
  • @AdriannaTyszkiewicz don't use that serializer to begin with. It's deprecated and even ASP.NET Web API uses Json.NET instead. – Panagiotis Kanavos May 21 '19 at 11:25
  • @AdriannaTyszkiewicz as for the rest of the code, if you want to write to a *file*, there's no reason to use a MemoryStream. Just write to the file stream. You should use JSON.NET and simplify the code. A simple` JsonConvert.SerializeObject(myObject)` will return a JSON string that you can write to a file. Or you can use a [JsonSerializer](https://www.newtonsoft.com/json/help/html/SerializingJSON.htm) to write directly to a stream – Panagiotis Kanavos May 21 '19 at 11:29
  • Are you sure you want to use [`FileMode.Open`](https://learn.microsoft.com/en-us/dotnet/api/system.io.filemode?view=netframework-4.8)? *Specifies that the operating system should open an existing file... A FileNotFoundException exception is thrown if the file does not exist.* Usually when serializing one uses `FileMode.Create` to create or overwrite the old file, or `Append` to create or append to the old file. – dbc May 21 '19 at 18:19

0 Answers0