我在文本文件中有很多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();
}
}
由于您需要在数据上运行多个操作,最好的方法是将数据读取一次(或在数据更改时再次读取)并以支持支持快速查询。为了通过符号找到一行,您可以创建一个包含数据的字典。
以下样本使用广泛使用的JSON.NET库来解析JSON。
首先,您需要定义一个将json对象架构的类定义的类,例如:
class Row
{
[JsonProperty("sym")]
public string Symbol { get; set; }
public decimal vw { get; set; }
// ...
}
请注意,您可以使用JsonProperty
属性,以便能够将不同的名称分配给类的属性。
以下示例显示了如何从文件中读取数据以及如何将其转换为字典:
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"];