【问题标题】:ColdFusion 2018 processing an array of structsColdFusion 2018 处理结构数组
【发布时间】:2020-09-14 19:06:19
【问题描述】:

我在处理内部数组(变体)时遇到问题。获取类 java.lang.String 类型的对象不能用作数组

<cfset jsonData = deserializeJSON(httpResp.fileContent) />
    
<cfset products = jsonData.products>

<cfoutput>

    <cfloop array="#products#" index="x">   
        #x.id# - #x.handle# <br>
                    
        <cfset variants = "variants">
        
        <cfloop array="variants" index= "i">
            #i.barcode#
        </cfloop>
        
    </cfloop>    

</cfoutput>

【问题讨论】:

  • 你需要使用&lt;cfset variants = x.variants&gt;或者像&lt;cfloop array="#x.variants#" index= "i"&gt;一样直接在循环中使用。
  • 谢谢,它有效,但现在我收到“元素条码在 I 中未定义。”
  • 你得到“Object of type class java.lang.String cannot be used as an array”的原因是因为你在每个循环的products结构内部设置&lt;cfset variants = "variants"&gt;并覆盖variants元素。删除 cfset 并将循环数组更改为 #x.variants# ,它应该可以满足您的需求。
  • 然后对于#i.barcode#,如果没有定义,你可以给它#i.barcode?:""#默认为空字符串。

标签: arrays coldfusion cfloop coldfusion-2018


【解决方案1】:

在 RRK 的帮助下(不知道如何称赞他),我得以成功:

<cfset jsonData = deserializeJSON(httpResp.fileContent) />     
<cfset products = jsonData.products>
<cfoutput>  
    <cfloop array="#products#" index="x">   
        #x.id# - #x.handle# <br>
                    
        <cfset variants = "#x.variants#">           
        <cfloop array="#variants#" index= "i">
            <cfif IsDefined("i.barcode") and i.barcode is not "">
                #i.barcode# <br>
            </cfif>
        </cfloop>
        
    </cfloop>        
</cfoutput>

【讨论】:

  • 查看我上面关于使用 Elvis Operator 而不是 isDefined 的评论。或者使用structKeyExists 而不是isDefined
【解决方案2】:

尝试使用 cfscript

<cfscript>
jsonData = deserializeJSON(httpResp.fileContent);
    
products = jsonData.products;


for (product in products) {
   writeoutput("#product.id# - #product.handle# <br>");

   for (variant in product.variants) {
     writeoutput(variant.barcode);
   }  
}
</cfscript>

【讨论】:

  • 好收获。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
  • 1970-01-01
相关资源
最近更新 更多