C# – How to parse a dynamically changing Json file? (c#)

cjsonparsingrestruntime

So I know a little bit about parsing Json data but not too much so pardon if I am not describing everything as I should. Lets use this Json file as an example:

{  
  "firstname": "John",  
  "lastname": "Smith",  
  "age": 25,  
  "address": {  
    "street address": "21 2nd Street",  
    "city": "New York",  
    "state": "NY",  
    "postal code": "10021"  
  },  
  "phonenumbers": [  
    {  
      "type": "home",  
      "number": "212 555-1234"  
    },  
    {  
      "type": "fax",  
      "number": "646 555-4567"  
    }  
  ],  
  "sex": {  
    "type": "male"  
  }  
}  

I know that if I want to parse this json data I will first have to create a class with these names in script (I didnt write them all out I know)

public class JsonClass
{
    string firstname;
    List<phonenumberlist> phonenumbers;
}

public class phonenumberlist
{
    string type;
    string number;
}

but my question is what if I want to dynamically change the json file and how can I go about setting up new classes dynamically in accordance to my dynamically changing json file? for example If i add to the Json file under phone numbers list.

"areaCodeLocation": "new york"

Then I wouldnt be able to parse it since I would have to manually go into my code and update the class I had written. Or what if I wanted to add something else? like
"height" : "6"

Basically what Im asking is how to dynamically build a parser to change according to my dynamically changing json, if that even is possible? Thanks!

Edit: To further clarify what I am trying to achieve. I will host a json file on the internet and I will parse it when my program starts. This is not a problem normally because everything is properly initialized written through classes in the code. But In the event I decide to add more information to my json file like "areaCodeLocation" or "height" as shown above = this will not be parsed because It is not initialized in the class.

What I want to do, if possible, is for the json file to be parsed through code, including setting up the classes, which will allow the program to parse any additional information I may want to add to the json file (hosted online) without myself going in to my code and manually adding new classes for parsing. This is so my users will not have to update the program every time I decide to add something new to the json file since it will be done within the code.

Best Answer

Pardon me if I've misunderstood your question, but the way I see it Newtonsoft.Json library has JObject class which actually represents dynamic JSON piece. Here's the snippet code which shows how you can query it to get only the properties you're interested in your business logic.