简体   繁体   English

如何在linq查询中反序列化json对象?

[英]How to deseralize json object in linq query?

I am fetching json data from txt file in linq and performing some actions on that to making the process fast. 我要从linq中的txt文件中获取json数据,并对此执行一些操作以加快处理速度。 but when I am trying to call that query then it's showing me an error for deserialization of json object. 但是当我尝试调用该查询时,它向我显示了json对象反序列化的错误。 So how to deserialize it? 那么如何反序列化呢?

I am getting error like 我收到类似的错误

Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List1[MMF.LiveAMData]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. 无法将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'System.Collections.Generic.List1 [MMF.LiveAMData]',因为该类型需要JSON数组(例如[1,2,3] )正确反序列化。

I search to solve this issue but almost all answers performing desrialization without linq. 我寻求解决此问题,但是几乎所有答案都执行无linq的反序列化。 I need to use linq due to time latency. 由于时间延迟,我需要使用linq。

Below is my method which I am calling 下面是我正在调用的方法

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

and below is my class object which I am using 下面是我正在使用的类对象

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

You're trying to deserialize a JSON array, but you're trimming the [ and ] parts so that it's no longer a JSON array. 您正在尝试反序列化JSON数组,但是您正在修剪[]部分,使其不再是JSON数组。 Remove the trim line: 删除装饰线:

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

If each line of your file is a JSON array like so: 如果文件的每一行都是这样的JSON数组:

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

Your trim line will change it to this invalid JSON: 您的装饰线会将其更改为以下无效的JSON:

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

Which certainly can't be deserialized to a List<LiveAMData>> 当然不能将其反序列化为List<LiveAMData>>

As you are deserializing each object individually, you don't need the List type in the DeserializeObject call. 在逐个反序列化每个对象时,在DeserializeObject调用中不需要List类型。 Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM