我有一个json节点,我想检查一下它是否为数组。如果节点是数组,则每个值都应为短值。因此,对于每个值,我正在使用isNumber()API检查它是否为数字。但是我想知道这个数字是否为Short。怎么做? 代码:
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,但始终为false。
答案 0 :(得分:0)
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;
}
}