What would be the correct approach?

JenniferLostTheWar

New member
Joined
Dec 22, 2015
Messages
1
Programming Experience
Beginner
Hello I?m very new to programming and I am writing a read only address book using the json.net library. Each person in the address book has about 30 values. However sometimes a person may be missing a couple of values.


When the value is missing the program locks and then crashes. So I implemented a try/catch around each value. However I get a feeling that isn?t the right way to approach this.


What would be the optimal way of approaching this? I thought about writing a function that will intake the values and then output the result. This way I would only have to do a try/catch 1 time in side that function.


Just don?t want to learn any bad habits.




C#:
JObject jsonObj = JObject.Parse(jsonData);
try
{
    key1 = jsonObj["data"]["name"].ToString();
}
catch
{
    key1 = "Not There";
}
try
{
    key2 = jsonObj["data"]["phone"].ToString();
}
catch
{
    key2 = "Not There";
}


try
{
    key3 = jsonObj["data"]["address"]["city"].ToString();
}
catch
{
    key2 = "Not There";
}
 

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
1,194
Location
Norway
Programming Experience
10+
Some options for handling missing key shown here: c# - json.net has key method? - Stack Overflow
The problem with your code is mainly that you call .ToString on something that might be null.

You can also define a type and serialize data to it, see for example: c# - Should I set any attribute for the optional fields in case of JSON.NET - Stack Overflow
For serialization you can also define part of the field and let any other go into JsonExtensionData dictionary, for example: c# - Deserialize known and unknown JSON fields into a CLR object with JSON.NET - Stack Overflow
 
Top Bottom