title: Create Jackson ObjectNode from Object
body: <p>I need to add a new item to an existing <code>ObjectNode</code>, given a key and a value. The value is specified as an <code>Object</code> in the method sig and <em>should</em> be one of the types that ObjectNode.set() accepts (<code>String</code>, <code>Integer</code>, <code>Boolean</code>, etc). But I can't just do <code>myObjectNode.set(key, value);</code> because value is just an <code>Object</code> and of course I get a <em>"not applicable for the arguments (String, Object)"</em> error. </p>
  
  <p>My make-it-work solution is to create a function to check the <code>instanceof</code> and cast it to create a <code>ValueNode</code>:</p>
  
  <pre><code>private static ValueNode getValueNode(Object obj) {
    if (obj instanceof Integer) {
      return mapper.createObjectNode().numberNode((Integer)obj);
    }
    if (obj instanceof Boolean) {
      return mapper.createObjectNode().booleanNode((Boolean)obj);
    }
    //...Etc for all the types I expect
  }
  </code></pre>
  
  <p>..and then I can use <code>myObjectNode.set(key, getValueNode(value));</code></p>
  
  <p><strong>There must be a better way</strong> but I'm having trouble finding it. </p>
  
  <p>I'm guessing that there is a way to use <code>ObjectMapper</code> but how isn't clear to me at this point. For example <a href="https://stackoverflow.com/questions/15786129/converting-java-objects-to-json-with-jackson">I can write the value out as a string</a> but I need it as something I can set on my ObjectNode and needs to be the correct type (ie everything can't just be converted to a String).</p>