title: Jackson's SORT_PROPERTIES_ALPHABETICALLY for Map
body: <p>I use Jackson 2.5.0.
  I would like to write a method which takes arbitrary JSON-string and sorts every property by key alphabetically with Jackson. Including nested ones.</p>
  
  <p>I learned there is a <code>SORT_PROPERTIES_ALPHABETICALLY</code> feature of Jackson's ObjectMapper which I wanted to use in order to achieve my goal. So my initial code based on this idea is:</p>
  
  <pre><code>class FooBar {
      String foo
      String bar
  }
  
  def sortFields(String source) {
      def om = new ObjectMapper().configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
  
      def obj = om.readValue(source, Map.class)
      return om.writeValueAsString(obj)
  }
  
  println sortFields('{"foo":"f","bar":"b"}')
  </code></pre>
  
  <p>Notice that I can't know ahead what structure input JSON has so Jackson unmarshalls it as a <code>Map</code> by default (<code>LinkedHashMap</code> to be more precise).
  I expected it to output a string with keys sorted alphabetically:</p>
  
  <blockquote>
    <p>{"bar":"b","foo":"f"}</p>
  </blockquote>
  
  <p>Unfortunately with the snippet above <code>SORT_PROPERTIES_ALPHABETICALLY</code> does not work when object to serialize is a <code>Map</code>. If I replace <code>Map.class</code> with <code>FooBar.class</code> my JSON properties will be sorted as expected. But as I said, I can't know ahead a type of input JSON and have a class in my code for any type possible. What other options do I have with Jackson?</p>