Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Json data from text file C#

Tags:

json

c#

list

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 ?

like image 545
Letoncse Avatar asked Jul 04 '16 08:07

Letoncse


2 Answers

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];
like image 176
huysentruitw Avatar answered Oct 16 '22 12:10

huysentruitw


You need to install Newtonsoft.Json and then you need use it:

using Newtonsoft.Json;

class Program
    {
         public void LoadJson()
        {
            using (StreamReader r = new StreamReader("file.json"))
            {
                string json = r.ReadToEnd();
                List<SponsorInfo> items = JsonConvert.DeserializeObject<List<SponsorInfo>>(json);
            }
        }


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




        static void Main(string[] args)
        {
            dynamic array = JsonConvert.DeserializeObject(json);
            foreach (var item in array)
            {
                Console.WriteLine("{0} {1}", item.temp, item.vcc);
            } 

        }

    }
like image 45
Vicky Avatar answered Oct 16 '22 11:10

Vicky