简体   繁体   中英

Avoid object null reference exception when accessing sub-elements that may or may not exist (JSON)

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM