agentgonzo
agentgonzo

Reputation: 3643

Creating an inherited custom class from Jackson's ObjectNode

I'm wanting to extend ObjectNode such that I can have a couple of helper methods to get a couple of specific fields from the JSON. eg

public class MyNode extends ObjectNode {
  public void Long getTimestamp() {
    return this.get(HEADER).get(TIMESTAMP).asLong();
  }
}

But the problem I have is that ObjectMapper().readTree("<...my JSON here...>") returns a JsonNode object which I obviously can't cast to MyNode.

And there's no constructer of ObjectNode that takes another JsonNode. What's the best way to convert the string representation of my JSON into a MyNode object?

Upvotes: 0

Views: 1563

Answers (1)

StaxMan
StaxMan

Reputation: 116522

You need to create custom JsonNodeFactory (and register it with ObjectMapper), and that should allow you to provide custom implementations -- they must be sub-classes; but you only need to create your own instance, and then deserializers can populate them. So you should not need to use copy constructors or convert. Rather, factory is called to create new empty instances.

Upvotes: 1

Related Questions