如何使用xpath / jsonpath从C#中的txt文件中查找特定的json元素?

时间:2019-02-18 14:31:10

标签: c# json filestream jsonpath

我将大量JSON格式的数据转换为文本文件,格式如下:

[{"ev":"AM","sym":"TMHC","v":1000,"av":74917,"op":18.92,"vw":19.1305,"o":19.13,"c":19.15,"h":19.15,"l":19.13,"a":19.143,"z":90,"n":1,"s":1549380300000,"e":1549380360000},{"ev":"AM","sym":"SPYG","v":7103,"av":184266,"op":35.27,"vw":35.3148,"o":35.3264,"c":35.34,"h":35.34,"l":35.3258,"a":35.3345,"z":710,"n":1,"s":1549380300000,"e":1549380360000},
{"ev":"AM","sym":"AAPL","v":73,"av":1866,"op":35.27,"vw":35.3148,"o":35.3264,"c":35.34,"h":35.34,"l":35.3258,"a":35.3345,"z":710,"n":1,"s":1549380300000,"e":1549380360000}]

所以我需要找到特定符号的json元素。就像我使用AAPL一样,它会为我们提供来自txt文件的所有AAPL元素数据。像

{"ev":"AM","sym":"AAPL","v":73,"av":1866,"op":35.27,"vw":35.3148,"o":35.3264,"c":35.34,"h":35.34,"l":35.3258,"a":35.3345,"z":710,"n":1,"s":1549380300000,"e":1549380360000}

所以,请您能帮助我该怎么做?

static void xPathUsing()
{
  const string filePath = @"D:\Aggregate_Minute_AAPL.txt";
  using (StreamReader r = new StreamReader(filePath))
  {
      string json = r.ReadToEnd();
  }
}

1 个答案:

答案 0 :(得分:0)

由于您需要对数据执行多项操作,因此最好的方法是一次(或每次数据更改时)将数据读入内存,并以支持快速查询的方式保存它们。为了通过符号查找行,您可以创建一个保存数据的字典。

以下示例使用了广泛使用的JSON.NET库来解析JSON。

首先,您需要定义一个与JSON对象的模式相似的类,例如:

class Row
{
    [JsonProperty("sym")]
    public string Symbol { get; set; }
    public decimal vw { get; set; }
    // ...
}

请注意,您可以使用JsonProperty属性,以便为该类的属性分配与JSON中不同的名称。

以下示例显示了如何从文件读取数据以及如何将其转换为字典:

var input = File.ReadAllText("C:\\Temp\\abc.json");
var rows = JsonConvert.DeserializeObject<IEnumerable<Row>>(input);
var dict = rows.ToDictionary(x => x.Symbol, x => x, StringComparer.OrdinalIgnoreCase);

准备完一次字典后,可以使用索引器获取相应的行:

var aaplRow = dict["AAPL"];