从文本文件C#中读取Json数据

编程入门 行业动态 更新时间:2024-10-24 16:31:24
本文介绍了从文本文件C#中读取Json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个文本文件,其中包含以下格式数据

I have a text file with below format data

[ { "SponsorID": 1, "FirstBAID": 7395836 }, { "SponsorID": 2, "FirstBAID": 3509279, "SecondBAID": 2947210 }, { "SponsorID": 3, "FirstBAID": 1776294, "SecondBAID": 6503843 }, { "SponsorID": 4, "FirstBAID": 8014528, "SecondBAID": 6203155 }, { "SponsorID": 5, "FirstBAID": 5968769, "SecondBAID": 7410195, "ThirdBAID":8950170, } ]

我想将此数据读取为列表&那么我需要通过SponsorID进行查询. 我已经创建了一个像这样的类

I want to read this data as a List & then i need to query by SponsorID. I have created a class like this

public class SponsorInfo { public decimal SponsorID { get; set; } public decimal FirstBAID { get; set; } public decimal SecondBAID { get; set; } public decimal ThirdBAID { get; set; } }

现在如何读取文本文件数据&绑定 SponsorInfo 类?

Now how can i read text file data & bind SponsorInfo class ?

推荐答案

从NuGet程序包管理器控制台安装Newtonsoft.Json nuget程序包:

Install Newtonsoft.Json nuget package from NuGet package manager console:

PM> Install-Package Newtonsoft.Json

然后:

var jsonText = File.ReadAllText("filepath"); var sponsors = JsonConvert.DeserializeObject<IList<SponsorInfo>>(jsonText);

要在SponsorID上进行查询,可以使用LINQ:

To query on SponsorID you can use LINQ:

var sponsor5 = sponsors.FirstOrDefault(x => x.SponsorID == 5);

如果您经常需要按SponsorID查找,则可以将结果转换为键为SponsorID的字典.这将提高性能,因为它不需要为每个查找都对整个列表进行枚举.我还建议您将SponsorID的类型更改为int而不是decimal.

If you often need a lookup by SponsorID, you could convert the result to a dictionary where the key is the SponsorID. This will improve performance as it doesn't need to enumerate through the entire list for each lookup. I also suggest you change the type of SponsorID to an int instead of a decimal.

var sponsorsById = sponsors.ToDictionary(x => x.SponsorID);

然后,您可以像这样轻松地访问它:

Then you can easily access it like:

if (sponsorsById.ContainsKey(5)) var sponsor5 = sponsorsById[5];

更多推荐

从文本文件C#中读取Json数据

本文发布于:2023-11-06 05:19:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562807.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件   数据   Json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!