parse only certain values which can be found in multiple objects from a json file

Viewed 42

I've never tried to parse JSON files before, so I don't really know what to do in this case:

Each object in the JSON file is an example but with different names. They can also hold extra values that most of the rest doesn't have. My goal is to get only le, lh, li and the count value inside them from every example and ignore the rest.

This is an example of the JSON file:

{
    "example": {
       "image": "exampleInage.jpg",
       "le": {
           "level": 6.1,
           "count": 50,
           "ars": {
               "format": "[!!12:|<|<o!!]",
               "1": "ex"
           }
       },
       "lh": {
           "level": 11.6,
           "count": 400,
           "ars": "ex"
       },
       "li": {
           "level": 14.6,
           "count": 613
       },
       "ar": "C",
       "oars": {
           "format": "<<<1>>> -Er0-",
           "1": "oex"
       },
       "il": "pex",
       "version": "2.4.0"
   }
}

I wanted to parse each le, lh, li into an Ex class which looks like this:

class Ex
    {
        string title;
        int count;
        string dN;
        double dL;

        public Ex (string _title, int _count, string _dN, double _dL)
        {
            title = _title;
            count = _count;
            dN = _dN;
            dL = _dL;
        }
    }

As of now, I've not found a solution that'd work for me yet.

my question is similar to this one, but the objects not only have different names, but also slightly different varriables, but there are a few that is the same in each of them. my goal is to parse only those.

1 Answers

Step by step, what I would do:

  • Get your json, go to a class generator like https://json2csharp.com/ and generate the classes.

  • Select Add JsonProperty Attributes (this will make use Newtonsoft.Json nuget)

  • Install Newtonsoft.Json nuget package

  • Deserialize the object from a string

    var json = @"YOUR JSON GOES HERE OR GET IT FROM A FILE";

    var example = JsonConvert.DeserializeObject(json);

    Console.WriteLine(example.Lh.Level);

Related