简体   繁体   English

如何在 razor 页面中检查 json 属性是否为空

[英]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 In.Net core Razor页面如何查看“payments”是否为空

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'它说 RuntimeBinderException: 'Newtonsoft.Json.Linq.JArray' 不包含 '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. JArray不公开 Length 属性,但确实公开了HasValuesCount属性,这些属性显示JArray是否包含子标记。

You can change your check to the following:您可以将支票更改为以下内容:

@if (@transaction.payments.HasValues)

If your Json data is in JObject form, this could work:如果您的 Json 数据是JObject形式,这可以工作:

@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.如果您的 JSON 数据采用 object 形式。 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 *@
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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