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

问题描述

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

序列化float数组,然后反序列化同一文件。

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...