Read and Parse a Json File in C#

Parsing json file in c# to get into all sections and properties

You can use the built-in JSON library in the .net core

using System.Text.Json;

add the following model definition

 public class Rootobject
{
public Company Company { get; set; }
}

public class Company
{
public Employee[] Employees { get; set; }
}

public class Employee
{
public string EmpName { get; set; }
public string EmpGender { get; set; }
public string Age { get; set; }
}

deserialize your object like the following

string jsonData = File.ReadAllText("data.json");
Rootobject ob = JsonSerializer.Deserialize<Rootobject>(jsonData);

now you have ob in you c# represent your JSON as C# object

I don't want to build a model for this

if you use Visual Studio you can auto generate your model classes required for your JSON as described here the above models are auto generated by Visual Studio

Loading a .json file into c# program

You really should use an established library, such as Newtonsoft.Json (which even Microsoft uses for frameworks such as MVC and WebAPI), or .NET's built-in JavascriptSerializer.

Here's a sample of reading JSON using Newtonsoft.Json:

JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));

// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject) JToken.ReadFrom(reader);
}

Read Json data from text file C#

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

C# .NET5 Single File Application Read and Parse Json / Txt or other file formats from directory

You have to use Directory.GetCurrentDirectory() instead of AppDomain.CurrentDomain.BaseDirectory.

using Newtonsoft.Json;

public static Settings LoadSettingsFile()
{
string currentPath = Directory.GetCurrentDirectory();
string directoryPath = @$"{currentPath}\sources";
string path = @$"{directoryPath}\settings.json";

string jsonResult = File.ReadAllText(path);
return JsonConvert.DeserializeObject<Settings>(jsonResult);
}

If you are reading a JSON file then, you can parse it to your class with Newtonsoft. This works for txt or other file formats too.

Parsing json file to get out data

Using Json2CSharp, the following class(es) models your json.

public class Fridge
{
public string color { get; set; }
public string comment { get; set; }
public int version { get; set; }
public int date { get; set; }
public int features { get; set; }
public string purpose { get; set; }
public List<int> format { get; set; }
public List<List<int>> build { get; set; }
}

public class RootObject
{
public string modelName { get; set; }
public Fridge Fridge { get; set; }
}

Note that you can also do this in Visual Studio, as long as your json string is valid. Just go to Edit->Paste Special..

You can then consume as follows:

var myObject=JsonConvert.DeserializeObject<RootObject>();
//get the format list
var formats=myObject.Fridge.format;
var build=myObject.Fridge.build;

Parse json and get values using System.Text.Json

Well, first of all 12Mb doesn't seem to be a very large file - but that's up to you.

You can create your custom collection, implement ICollection<Location>.Add (for example, inheriting from Collection<Location>) method and filter deserialized instances of Location there.

For example:

public class FilteredLocationCollection: Collection<Location>
{
public FilterCollection(double lat, double lng)
{
Lat = lat;
Lng = lng;
}

public double Lat { get; }
public double Lng { get; }

protected override void InsertItem(int index, Location item)
{
if (item.Latitude == Lat && item.Longitude == Lng) /* here check item for corresponding to desired Lat\Lng */)
base.InsertItem(index, item);
}
}

Then, you'll be able to deserialize:

var locations = JsonSerializer.Deserialize<FilteredLocationCollection>(filepath?);

And locations will contain only those instances that correspond to your condition.

BTW, to correctly deserialize your JSON into Location instance, you should provide attributes for fields (as long as property names in JSON don't match names of properties in your class) :

public class Location
{
[JsonPropertyName('country')]
public string Country { get; set; }
[JsonPropertyName('name')]
public string City { get; set; }
[JsonPropertyName('lat')]
public double Latitude { get; set; }
[JsonPropertyName('lng')]
public double Longitude { get; set; }
}


Related Topics



Leave a reply



Submit