0

我正在从 linq 中的 txt 文件中获取 json 数据,并对其执行一些操作以加快处理速度。但是当我试图调用该查询时,它向我显示了一个反序列化 json 对象的错误。那么如何反序列化呢?

我收到类似的错误

无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List1[MMF.LiveAMData]”,因为该类型需要 JSON 数组(例如 [1,2,3] ) 以正确反序列化。

我搜索以解决此问题,但几乎所有答案都在没有 linq 的情况下执行反序列化。由于时间延迟,我需要使用 linq。

以下是我正在调用的方法

public static void something()
      {
          File.ReadLines(filePath)
              .AsParallel()
              .Select(x => x.TrimStart('[').TrimEnd(']'))
              .Select(JsonConvert.DeserializeObject<List<LiveAMData>>)
              .ForAll(WriteRecord);
      }

下面是我正在使用的类对象

public class LiveAMData
    {
        public string ev { get; set; }
        public string sym { get; set; }
    }
4

2 回答 2

3

您正在尝试反序列化 JSON 数组,但您正在修剪[and]部分,使其不再是 JSON 数组。删除修剪线:

public static void something()
{
    File.ReadLines(filePath)
        .AsParallel()
        .Select(JsonConvert.DeserializeObject<List<LiveAMData>>)
        .ForAll(WriteRecord);
}

如果文件的每一行都是 JSON 数组,如下所示:

[{"ev":"Test1", "sym": "test"},{"ev":"Test2", "sym": "test"}]

您的修剪线会将其更改为此无效的 JSON:

{"ev":"Test1", "sym": "test"},{"ev":"Test2", "sym": "test"}

这当然不能反序列化为List<LiveAMData>>

于 2019-02-15T08:05:44.847 回答
0

当您单独反序列化每个对象时,您不需要调用List中的类型 。DeserializeObject试试这个:

        public static void something()
        {
            File.ReadLines(filePath)
                .AsParallel()
                .Select(x => x.TrimStart('[').TrimEnd(']'))
                .Select(JsonConvert.DeserializeObject<LiveAMData>)
                .ForAll(WriteRecord);
        }
于 2019-02-15T08:08:42.890 回答