[英]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. 我已经将json数据转换为c#类,并希望将提取数据插入到我的数据库中。
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
NullReferenceException未处理
Object reference not set to an instance of an object.你调用的对象是空的。
it's very difficult to check existance something like this : 像这样检查存在性是非常困难的:
vn.price.message
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. 上层对象( 作为insert方法中的参数 )有错误,因为json数据有时没有价格元素,因此在t之后没有消息 。
how can i convert such these parameters to null? 我如何将这些参数转换为null?
EDIT : 编辑:
here is two related of my properties in c# classes : 这是我在c#类中的两个相关属性:
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? 为此类消息属性设置默认null值的最快方法是什么?
Use the JToken.SelectToken()
method to look up the value. 使用
JToken.SelectToken()
方法查找值。 If it exists in the full path, the token will be returned and you can retrieve your value. 如果它存在于完整路径中,则将返回令牌,您可以检索值。 Otherwise it will be null.
否则它将为null。
var token = obj.SelectToken("vn.price.message");
if (token != null)
{
// do stuff with token
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.