我的主動選擇反應參考引數讀取以下 JSON 檔案
{
"Name": "Tom",
"Age": "25",
"Subjects": ["English", "Physics", "Chemistry", "Biology", "Maths"]
}
參考的引數是file, Nos(之前的主動選擇反應引數),它是一個單選按鈕,值為 1、2、3、4、5
現在基于 的值Nos,我必須顯示主題。這就是我所做的:
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def config = jsonSlurper.parse(new File(file))
return config.Subjects
使用上面的代碼,輸出是,
1. English
2. Physics
3. Chemistry
4. Biology
5. Maths
如果我嘗試回傳config.Subjects.take(Nos)or config.Subjects.subList(Nos),我期望,如果Nos = 3是
1. English
2. Physics
3. Chemistry
但我什么也沒看到。然后我試了,
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def config = jsonSlurper.parse(new File(file))
list = []
i = 0
config.Subjects.each {
while (i < Nos){
list.add "$it".toString()
i = i 1
}
}
return list
但是這一次,我1. English總是看到,無論我選擇哪個單選按鈕。我哪里錯了?
uj5u.com熱心網友回復:
你的代碼幾乎是正確的。您應該使用take切片串列。例如take(2)將回傳前兩個元素。所以不要回傳config.Subjects,而是嘗試回傳(config.Subjects).take(Nos)
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def config = jsonSlurper.parse(new File(file))
return (config.Subjects).take(Nos)
如果 Nos 是字串,則將其轉換為整數并像這樣回傳
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def config = jsonSlurper.parse(new File(file))
return (config.Subjects).take(Nos.toInteger())
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/447708.html
