Marko
Marko

Reputation: 522

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?

Upvotes: 3

Views: 1207

Answers (3)

Yan Pak
Yan Pak

Reputation: 1867

You can use combination of @JsonAnyGetter and @JsonIgnore annotations also. It will unwrap key-value pairs of the HashMap like they are elements of the parent object and will not include object HashMap like a field.

@JsonAnyGetter
@JsonIgnore // sometimes not required
private Map<String,Customer> customers = new HashMap<>();  

result:

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

Perhaps, this will be useful for someone.

Important! If root element and nested one which should be unwrapped have fields with the same names then resulting json object will have all of them, shortly said - it results in duplicated fields.

From @JsonAnyGetter's documentation:

Marker annotation that can be used to define a non-static, no-argument method
to be an "any getter";
accessor for getting a set of key/ value pairs, to be serialized
as part of containing POJO (similar to unwrapping)
along with regular property values it has.
This typically serves as a counterpart to "any setter" mutators (see JsonAnySetter).
Note that the return type of annotated methods must be java. util. Map).
As with JsonAnySetter, only one property should be annotated with this annotation;
if multiple methods are annotated, an exception may be thrown.

Upvotes: 0

Emdadul Sawon
Emdadul Sawon

Reputation: 6077

Why not try this

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

Simply pass the Map, instead of Customer object.

Upvotes: 1

Filippo Fratoni
Filippo Fratoni

Reputation: 399

Try @JsonUnwrapped on the property Customers this can help you unwrap a nested level

Upvotes: 6

Related Questions