Piotr Supel
Piotr Supel

Reputation: 67

Jackson - Java Objects with List<Map<String,String>> to Json String conversion

I would like to generate JSON String from Java object

public class Resource {

String name;
List<Item> items;

public String resourceAsJson(Resource resource) throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.writeValueAsString(resource);
}

Where Item

public class Item {
    Map<String, String> systemFields;
    Map<String, String> dataFields;
}

The form of the JSON String at this moment is

{
"name": "Person",
"items": [
    {
        "systemFields": {
            "systemField1": "xxx",
            "systemField2": "xxx",
            "systemField3": "x"
        },
        "dataFields": {
            "dataField1": "xxx",
            "dataField2": "xxx",
            "dataField3": "x"
        }
    }
    ]
}

What I try to obtain is the different form of JSON (ommiting the Item and have "system fields" "data fields" in one Json table)

{
"Person":[
        {
        "systemField1": "xxx",
        "systemField2": "xxx",
        "systemField3": "Warsaw",
        "dataField1": "xxx",
        "dataField2": "xxx",
        "dataField3": "xxx"
        }
    ]
}

Is there a way to do this with Jackson without changing the model?

Upvotes: 2

Views: 700

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38645

In cases like this where default representation of POJO is not what you want you need to implement custom serialisers. In your case they could look like below:

class ResourceJsonSerializer extends JsonSerializer<Resource> {
    @Override
    public void serialize(Resource value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        gen.writeFieldName(value.getName());
        gen.writeObject(value.getItems());
        gen.writeEndObject();
    }
}

class ItemJsonSerializer extends JsonSerializer<Item> {

    @Override
    public void serialize(Item value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        writeMap(value.getSystemFields(), gen);
        writeMap(value.getDataFields(), gen);
        gen.writeEndObject();
    }

    private void writeMap(Map<String, String> map, JsonGenerator gen) throws IOException {
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                gen.writeStringField(entry.getKey(), entry.getValue());
            }
        }
    }
}

You can register them using com.fasterxml.jackson.databind.annotation.JsonSerialize annotation:

@JsonSerialize(using = ResourceJsonSerializer.class)
class Resource {

and:

@JsonSerialize(using = ItemJsonSerializer.class)
class Item {

Upvotes: 1

Related Questions