简体   繁体   中英

how to check a json property is empty or not in razor page

I've a sample response value like this

{{
  "transaction_order_line_items": [],
  "payments": [],
}}

In.Net core Razor page how to check the "payments" is empty or not

I tried this following way but it's not worked

 @if(@transaction.payments!=null)
 {
 }

As well tried

@if(@transaction.payments.Length==0)

it says RuntimeBinderException: 'Newtonsoft.Json.Linq.JArray' does not contain a definition for 'Length'

Please let me know how to check the value is empty or not

JArray does not expose a Length property, but it does expose both HasValues and Count properties that reveal whether or not the JArray contains child tokens.

You can change your check to the following:

@if (@transaction.payments.HasValues)

If your Json data is in JObject form, this could work:

@if(transaction["payments"] is JArray {Type: JTokenType.Array, Count: > 0} payments){
    @* do stuff with payments variable 
       but remember. Payments is essentialy an array of
       JToken objects. You need to use the proper syntax 
       to access them *@
}

If your JSON data is in object form. this could also work:

@* Using Linq *@

@if(transaction.payments.Any()} payments){
    @* do stuff with transaction.payments variable *@
}

@* Or using Count *@

@if(transaction.payments.Count > 0} payments){
    @* do stuff with transaction.payments variable *@
}

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