Unlike basic values, obtaining values from lists is slightly more involved, as multiple values are present. The main accessors for lists are
getList(Function<Object, T>):List<T>
getList(Function<Object, T>, List<T>):List<T>
getList(TypeToken<T>):List<T>
getList(TypeToken<T>, List<T>):List<T>
.
For the purposes of this example, the following sample will be used be used:
{
"modules" : {
"blockCheats" : {
"enabled" : true,
"counters" : [1,2,3,4, "hello", 1.22]
}
}
}
Whereas for basic values you can simply do:
root.getNode("modules", "blockCheats", "enabled").getBoolean(false);
This is not possible for a list. Instead you can do something like this:
root.getNode("modules", "counters").getList(new Function<Object, Integer>(
@Override
public Integer apply(Object input) {
if (input instanceof Integer) {
return (Integer) input;
}
return null;
}
)
The above code will return a list containing [1,2,3,4]
. This can also shortened down using lambda expression:
root.getNode("modules").getList(input -> return input instanceof Integer ? (Integer) input : null);
However you may notice that running the same checks again and again may be inefficient and can potentially cause errors. Configurate provides a handy utility to handle that for you. The above example can be replaced by:
import ninja.leaping.configurate.Types;
root.getNode("modules","counters").getList(new Function<Object, Integer> {
@Override
public Integer apply(Object input) {
return Types.asInt(input)
}
}
Or simply:
import ninja.leaping.configurate.Types;
root.getNode("modules", "counters").getList(Types::asInt);