简体   繁体   中英

Counter in Java JsonPath expression

I am trying to use counter in JSON Path expression and getting JSONPath error java.lang.numberFormatException

    for (int counter = 0; counter < ids.size(); counter++) {
        tmp_rules = JsonPath.read(jsonFile, "$..orders[counter].rule");
        for (int counter2 = 0; counter2 < tmp_rules.size();counter2++){
            if (
                    (JsonPath.read(jsonFile, "$..orders[counter].rule[counter2]") == 1) &&
                    (JsonPath.read(jsonFile, "$..orders[counter].asked[counter2]")) != 0) {
                       end_id.add(JsonPath.read(jsonFile, "$..id[counter]"));
                       end_rule.add(JsonPath.read(jsonFile, "$..orders[counter].rule[counter2]"));
                       end_asked.add(JsonPath.read(jsonFile,"$..orders[counter].asked[counter2]"));
            }
        }
    }

Your JSON path expressions are not valid, since you use counter and counter2 strings as indexing arrays. You should rather use the values of your loop variables in the path expressions:

for (int counter = 0; counter < ids.size(); counter++) {
    tmp_rules = JsonPath.read(jsonFile, "$..orders[" + counter + "].rule");
    for (int counter2 = 0; counter2 < tmp_rules.size();counter2++){
        if (
                (JsonPath.read(jsonFile, "$..orders[" + counter + "].rule[" + counter2 + "]") == 1) &&
                (JsonPath.read(jsonFile, "$..orders[" + counter + "].asked[" + counter2 + "]")) != 0) {
                   end_id.add(JsonPath.read(jsonFile, "$..id[" + counter + "]"));
                   end_rule.add(JsonPath.read(jsonFile, "$..orders[" + counter + "].rule[" + counter2 + "]"));
                   end_asked.add(JsonPath.read(jsonFile,"$..orders[" + counter + "].asked[" + counter2 + "]"));
        }
    }
}

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