I am trying to create JSON in Java using the Jackson Streaming API. I am able to create everything and it's working fine. However, I have a scenario in my recurse method where I need to identify if the current context is Object
or Array
is there any default method in Jackson which can give me the current incoming context.
As we can see from the below code I am currently using the arrayFlag
to make the decision whether an Array
has been started by JsonGenerator
if so then I am making few decisions. Similarly, now I need to set a flag for Object
to see if the Object
has been created. I was wondering if there is any default method in JsonGenerator
that can give if the current incoming context is Array
, Object
or String
etc so that I can use the direct Method
instead of the method instead of these FLags to detect the Array
, Object
etc.
//Recurse method which will be called for various elements
private static boolean arrayFlag = false;
private static void createJson(final JsonGenerator jsonGenerator, final Map<String, List<MyClass>> values){
for (Map.Entry<String, List<MyClass>> elements : values.entrySet()) {
final String parent = elements.getKey();
final List<MyClass> children = elements.getValue();
//Calling another method to get the various type such as Object, Array, String etc
final String type = getType(parent);
if(type.equalsIgnoreCase("object")){
// If the Array is started then create Object without Name
if (arrayFlag) {
children.forEach((child) -> {
jsonGenerator.writeStartObject();
if (child.getChildren().size() > 0) {
createJson(jsonGenerator,child.getChildren());
});
});
}else{
//If array is not Started then create Object with NAME
jsonGenerator.writeFieldName(parent);
jsonGenerator.writeStartObject();
children.forEach((child) -> {
createJson(jsonGenerator, child.getChildren());
});
jsonGenerator.writeEndObject();
}
}else if (type.equalsIgnoreCase("array")) {
jsonGenerator.writeFieldName(parent);
jsonGenerator.writeStartArray();
arrayFlag = true;
children.forEach((child) -> {
createJson(jsonGenerator, child.getChildren());
});
jsonGenerator.writeEndArray();
arrayFlag = false;
}
}