javajsonjackson

JSON Serialize HashMap as root element


I have a class which is basically a wrapper for a HashMap. I would like to serialize this class with Jackson to an JSON object without any wrapping element.

   public class Customers {

        @JsonProperty
        private Map<String,Customer> customers = new HashMap<>();

        ...     

    }

Current serialization looks like this:

{
   "Customers":{
       "customers":{
          "keyX":{...},
          "keyY":{...},
          "keyZ":{...}
}

But I want to have this:

{
   "keyX":{...},
   "keyY":{...},
   "keyZ":{...}
}

How can I reach it?


Solution

  • Why not try this

    jsonString = mapper.writeValueAsString(customerObj.getCustomers());
    

    Simply pass the Map, instead of Customer object.