title: Serialization of root primitive objects with Jackson
body: <p>I am facing the following problems. When Jackson serializer is passed a wrapped primitive for serialization, this primitive is serialized as is, for example:</p>
  
  <pre><code>objectMapper = new ObjectMapper();
  
  StringWriter w = new StringWriter();
  objectMapper.writeValue(w, Integer.valueOf(10));
  System.out.println(w.toString());
  </code></pre>
  
  <p>produces <code>10</code> as output. However <code>10</code> is not a valid JSON (according to <a href="http://jsonlint.com/" rel="noreferrer">jsonlint</a>) and should be wrapped either in square brackets (<code>[10]</code>, so it will be a single-element array) or in curly brackets (<code>{value:10}</code>, so it will be an object with dummy property). The problem affects numbers, <code>java.lang.String</code>, <code>java.util.Date</code>, ...</p>
  
  <p>My question is: How to make Jackson to perform the wrapping? Shouldn't Jackson always produce a valid JSON?</p>
  
  <p>I have analyzed Jackson behavior with <code>SerializationConfig.Feature.WRAP_ROOT_VALUE</code> enabled: it does not work as I expect. Primitives are now serialized to valid JSON (<code>{"Integer":10}</code>), but "normal" Java beans are also wrapped which is undesired (<code>{"MyBean":{"field":value, ...}}</code> instead of <code>{"field":value, ...}</code>).</p>
  
  <p>If somebody can advise how to customize Jackson, perhaps with custom serializer. The difficulty would be that it is necessary to distinguish the root primitive wrapper (which needs to be wrapped) from bean primitive property (does not need to be wrapped).</p>
  
  <p>To make the story complete: Jackson serializer is used as message convertor for Spring MVC, and I doubt it is fairly easy to write a hook to intercept serialization of primitives (which will not call Jackson but will simply return <code>"[" + String.toString(obj) + "]"</code> when necessary). So I would prefer the solution with tuned Jackson.</p>