0

I've converted a json data to c# classes and want to insert fetch data to my database.
here is my codes :

My_Json My_Json_res = JsonConvert.DeserializeObject<My_Json>(result_str_after_request);

Venue vn = My_Json_res.venue;
Contact vn_contact = My_Json_res.venue.venue_contact;
Location vn_location = My_Json_res.venue.venue_location;

DataLayer.venues.InsertRow(
        vn.venue_id,
        vn.venue_name,
        vn_contact.contact_phone,
        vn_contact.contact_twitter,
        vn_contact.contact_facebook,
        vn_contact.contact_facebookUsername,
        vn_contact.contact_facebookName,
        vn_location.location_address,
        vn_location.location_crossStreet,
        vn_location.location_lat,
        vn_location.location_lng,
        vn_location.location_distance,
        vn_location.location_postalCode,
        ...
     );

as you see i have many many sub elements and sometimes during Insert method i got below error :

NullReferenceException was unhandled
Object reference not set to an instance of an object.

it's very difficult to check existance something like this :

vn.price.message

the upper object(as parameter in insert method) has error because json data sometimes does not have price element so there is no message after thet.
how can i convert such these parameters to null?

EDIT :
here is two related of my properties in c# classes :

VENUE CLASS
[JsonProperty("price")]
public Price venue_price { get; set; }

PRICE CLASS
[JsonProperty("message")]
public string price_message { get; set; }

what is the quickest way to set default null value for such message properties?

SilverLight
  • 19,668
  • 65
  • 192
  • 300

1 Answers1

0

Use the JToken.SelectToken() method to look up the value. If it exists in the full path, the token will be returned and you can retrieve your value. Otherwise it will be null.

var token = obj.SelectToken("vn.price.message");
if (token != null)
{
    // do stuff with token
}
SilverLight
  • 19,668
  • 65
  • 192
  • 300
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • there are over 200 300 sub elements and more, i can't do that for all of them and looking for a way to convert all not existance elements to null automatically. any other idea? – SilverLight Nov 10 '14 at 17:38
  • Use a better data structure. Or create a recursive reflective method that checks each level and pulls out your data. – David L Nov 10 '14 at 17:40
  • @MoonLight: Why not? That's the way you structured your model. You are going to have to validate the values somehow. Whether you do that validation manually or let the libraries you use do that for you is your call. – Jeff Mercado Nov 10 '14 at 17:56