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



我正在使用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(file,typeof(float]]((">

投掷:Newtonsoft.Json.JsonSerializationException:"转换值时出错";[0.23,11.23,22.22]";键入"System.Single[]"。路径",第1行,位置20.

我相信我错用了Newtonsoft.Json库,但我找不到例子序列化基元。

环境:.net Core 3.1(控制台应用程序(Newtonsoft.Json 12.0.3

提前谢谢。

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

最新更新