Home > Mobile >  Parse json and get values using System.Text.Json
Parse json and get values using System.Text.Json

Time:10-01

I have very large json file with lots of data. Structure looks like this

 {
    "country": "AD",
    "name": "Pas de la Casa",
    "lat": "42.54277",
    "lng": "1.73361"
  },

In my current c# code I have coordinates, let's say

var lat = "42.53";
var lng = "1.74";

Is there some way to read JSON without parsing it completely into memory first as file is pretty big, around 12 Mb. Can somebody provide some code example how this can be done using System.Text.Json.

I understand that I should create a class, like:

public class Location
{
    public string Country { get; set; }
    public string City { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

Then deserialize it?

Location location = 
                JsonSerializer.Deserialize<Location>(filepath?);

However my question is:

  1. How to first search for most closely matching coordinates, like in my example they does not completely match, but I need to get the most closest one.
  2. After match has been found get Country and City out of JSON.

CodePudding user response:

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