在 C# 控制台应用程序中使用 Newtonsoft.Json 反序列化浮点数组的 JSON 时出错

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

我正在使用 Newtonsoft.Json 库,但我无法完成一个相当简单的任务:

序列化一个浮点数组,然后反序列化同一个文件。

我的控制台应用程序如下所示:

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

行: "var dx = (float[])serializer.Deserialize(文件, typeof(float[]));"

投掷: Newtonsoft.Json.JsonSerializationException: '将值“[0.23,11.23,22.22]”转换为类型 'System.Single[]' 时出错。路径 '',第 1 行,位置 20.'

我相信我没有使用 Newtonsoft.Json 库,但我找不到示例 序列化原语。

环境: .net Core 3.1(控制台应用程序) Newtonsoft.Json12.0.3

提前致谢。

您正在连载两次。 output 包含序列化数组,您正在将该字符串序列化为文件。您不需要 JSON 序列化程序来编写已经表示 JSON 值的文本。您可以为此使用 File.WriteAllText