So the company I've been working for has asked me to make a C# library for a client company who needs to access our API with .NET. So far I have a working library, but I keep having problems parsing optional properties. We use mongoDB on the backend, and mongoDB doesn't store properties that aren't provided even if they're defined in the schema.
For example, my schema may look like:
{
name:String,
id:Number,
phone:String,
email:String,
experience:[]
}
Where as I make the document:
{
name:"joe",
id:5,
phone:"222-222-2222",
}
The properties email
and experience
DO NOT exist in my document, so my JSON looks exactly as displayed above. These values are not required values however, but I still need to parse the rest of it. The problem is that when I parse the code above for all the possible values when I parse for email
or experience
the parser throws a Null Reference Exception, and with good reason because the value I'm trying to parse does not exist and the way I reference these values is like so:
JObject o=JObject.Parse(json); //parse json to JObject json object
string name=(string)o["name"];
int id=(int)o["id"];
string phone=(string)o["phone"];
string email=(string)o["emain"];
List<string> exp=o["experience"].Select(t => (string)t).ToList();
Now my code is a lot more objective, I using LINQ to create an object called Job
and a object Jobs
to store the JObject in a way where you can query certain values out of it using methods of the Jobs
object thats initialized with the original JSON string.
Thing is the only way I can think of to handle optional properties in the JSON is to try/catch each and every value. This seems very sloppy and the JSON I have to parse is about 40-50 properties in total. This seems like it would be extremely slow and a huge mess of code. I'm wondering if I can implement this is a cleaner more efficient way.