Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save efenderbosch/36354b0abc1083d63f70c44687e1cafb to your computer and use it in GitHub Desktop.
Save efenderbosch/36354b0abc1083d63f70c44687e1cafb to your computer and use it in GitHub Desktop.
Jackson Ignore Extra Wrapped Root
import java.io.IOException;
public class IgnoreExtraWrappedRootJsonParser extends JsonParserDelegate {
private final String rootName;
public IgnoreExtraWrappedRootJsonParser(JsonParser delegate, JavaType rootType) {
super(delegate);
JsonRootName jsonRootName = rootType.getRawClass().getAnnotation(JsonRootName.class);
rootName = jsonRootName == null ? null : "/" + jsonRootName.value();
}
@Override
@SuppressFBWarnings(value = "ITU_INAPPROPRIATE_TOSTRING_USE", justification = "no other way to find current path")
public JsonToken nextToken() throws IOException {
JsonToken nextToken = super.nextToken();
String currentPath = getParsingContext().pathAsPointer().toString();
if (rootName == null || currentPath.startsWith(rootName) || currentPath.isEmpty()) return nextToken;
// skip this token and try the next one
return nextToken();
}
}
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import java.io.IOException;
public class IgnoreExtraWrappedRootObjectMapper extends ObjectMapper {
private static final long serialVersionUID = 1L;
@Override
protected Object _unwrapAndDeserialize(JsonParser p,
DeserializationContext ctxt,
DeserializationConfig config,
JavaType rootType,
JsonDeserializer<Object> deser) throws IOException {
IgnoreExtraWrappedRootJsonParser ignoreExtraWrappedRootJsonParser =
new IgnoreExtraWrappedRootJsonParser(p, rootType);
return super._unwrapAndDeserialize(ignoreExtraWrappedRootJsonParser, ctxt, config, rootType, deser);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment