Search code examples
c#jsonconsole-applicationjson-deserializationprimitive-types

Error while deserializing the JSON of float array with Newtonsoft.Json in C# console app


I'm using Newtonsoft.Json library and i can't acomplish a rather simple task:

Serialize an array of floats and then deserialize the same file.

My console aplication looks like this:

var x_train = new float[3];

x_train[0] = 0.23f;
x_train[1] = 11.23f;
x_train[2] = 22.22f;

string output = JsonConvert.SerializeObject(x_train);

JsonSerializer serializer = new JsonSerializer();

using (StreamWriter sw = new StreamWriter(_pathToSerializedObjects + "\\x_train.json"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
    serializer.Serialize(writer, output);
}
//The file is serialized correctly, now the problem is this block of code:

// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(_pathToSerializedObjects + "\\x_train.json"))
{
    JsonSerializer serializer2 = new JsonSerializer();
    var dx = (float[])serializer.Deserialize(file, typeof(float[]));
    Console.WriteLine(dx[0]);
    Console.WriteLine(dx[1]);
    Console.WriteLine(dx[2]);
}

The line : "var dx = (float[])serializer.Deserialize(file, typeof(float[]));"

Throws: Newtonsoft.Json.JsonSerializationException: 'Error converting value "[0.23,11.23,22.22]" to type 'System.Single[]'. Path '', line 1, position 20.'

I believe that i'm missusing the Newtonsoft.Json library but i can't find examples of serializing primitives.

Environment: .net Core 3.1 (Console app) Newtonsoft.Json 12.0.3

Thanks in advance.


Solution

  • You are serializing twice. output contains serialized array and you are serializing that string to a file. You don't need JSON serializer to write text that already represents JSON value. You can use File.WriteAllText for that.