我有一个json节点,我想检查它是否是一个数组。如果节点是数组,那么每个值应该是一个短值。因此,对于每个值,我正在检查它是否是使用isNumber()API的数字。但是我想知道这个号码是不是短号。怎么做?码:
JsonNode attrNode = rootNode.path("product_id_anyof");
if ((attrNode.getNodeType() == JsonNodeType.ARRAY) { ///this part is working.
for (final JsonNode node : attrNode) {
if (!node.isShort()) { ///returns false even if the number is a short.
return false;
else
return true;
}
}
}
预期:如果给出了short,它应该返回true但它总是给出错误。
JSON
number
默认情况下读为int
,尝试检查给定的number
值是否为short
手动:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType;
public class Test {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
System.out.println(onlyShortsArray(mapper.readTree("[1,2,3,4]")));
System.out.println(onlyShortsArray(mapper.readTree("[1,2,3, 33333]")));
System.out.println(onlyShortsArray(mapper.readTree("[1,2,3, \"a\"]")));
}
private static boolean onlyShortsArray(JsonNode attrNode) {
if (attrNode.getNodeType() == JsonNodeType.ARRAY) {
for (final JsonNode node : attrNode) {
if (node.isInt()) {
try {
Short.valueOf(node.asText());
continue;
} catch (NumberFormatException e) {
return false;
}
}
return false;
}
return true;
}
return false;
}
}