All subclasses ValueNodein Jackson (JSON library) have different methods for getting the base value object, for example. IntNodehas getIntValue, BooleanNodehas getBooleanValue, etc.
Why is there no universal / polymorphic method, called simply getValue, which simply returns Object, and Objectsomewhere Integer, or Booleanso on, depending on the type of node Is the method called?
Or ... is there really such a method? I need such a method for my purposes, but it seems that the developers of the library did not find that adding such a method would be useful. Or ... for some reason, is this method missing?
My goal: in the code below, I look through the tree and create a structure composed only of HashMap, Object[]and basic Java types (eg Integer, Booleanetc.). If I had such a method, instead of all these if-else if-else if blocks , I would have only one method call (in the case when it JsonNodeis a leaf node, i.e. a subtype ValueNode). But it seems that I do not have such a method in Jackson. So I had to encode all these ugly if-else if-else if blocks .
CODE:
@SuppressWarnings({ "rawtypes", "unchecked" })
private static Object traverse(JsonNode nd) {
if (nd instanceof ObjectNode) {
ObjectNode ndd = (ObjectNode) nd;
HashMap mp = new HashMap();
Iterator<String> it = ndd.getFieldNames();
while (it.hasNext()) {
String s = it.next();
mp.put(s, traverse(ndd.get(s)));
}
return mp;
} else if (nd instanceof ArrayNode) {
ArrayNode ndd = (ArrayNode) nd;
Object[] arr = new Object[ndd.size()];
for (int i = 0; i < ndd.size(); i++) {
arr[i] = traverse(ndd.get(i));
}
return arr;
} else if (nd instanceof NullNode) {
return null;
} else if (nd instanceof BooleanNode) {
BooleanNode ndd = (BooleanNode) nd;
return ndd.getBooleanValue();
} else if (nd instanceof IntNode) {
IntNode ndd = (IntNode) nd;
return ndd.getIntValue();
} else if (nd instanceof LongNode) {
LongNode ndd = (LongNode) nd;
return ndd.getLongValue();
} else if (nd instanceof DoubleNode) {
DoubleNode ndd = (DoubleNode) nd;
return ndd.getDoubleValue();
} else if (nd instanceof DecimalNode) {
DecimalNode ndd = (DecimalNode) nd;
return ndd.getDecimalValue();
} else if (nd instanceof BigIntegerNode) {
BigIntegerNode ndd = (BigIntegerNode) nd;
return ndd.getBigIntegerValue();
} else if (nd instanceof TextNode) {
TextNode ndd = (TextNode) nd;
return ndd.getTextValue();
}
throw new IllegalStateException("Failed while traversing the JSON tree at node: ||| " + nd.asText() + " |||");
}
source
share