Liton Liton - 5 months ago 71
JSON Question

Read Json data from text file C#

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,
}
]


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; }
}


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

Answer

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

PM> Install-Package Newtonsoft.Json

Then:

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

To query on SponsorID you can use LINQ:

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

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];