Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening nested attributes in Jackson

Tags:

java

json

I have the need of defining a flat POJO that maps its (flat) attributes to a nested object in its JSON specification. Better explain with code

{
    "offset": 0,
    "pageSize": 10,
    "filter": {
        "key1":"value1",
        "key2": true,
        ....
    }
}

My POJO shall look like the following:

public class Pojo {
    private int offset;
    private int pageSize;

    private String key1;
    private boolean key2;
}

So far I have tried annotating those key properties with @JsonProperty with its value attribute

@JsonProperty("filter.key1")
private String key1;

But when I went into the MVC controller those properties, though set in JSON, were null in the decoded POJO.

How can I fix this? What did I do wrong?

I absolutely don't want to create nested subclasses

like image 231
usr-local-ΕΨΗΕΛΩΝ Avatar asked Feb 01 '16 10:02

usr-local-ΕΨΗΕΛΩΝ


People also ask

How do I flatten a nested JSON object?

Flatten a JSON object: var flatten = (function (isArray, wrapped) { return function (table) { return reduce("", {}, table); }; function reduce(path, accumulator, table) { if (isArray(table)) { var length = table.

How does Jackson read nested JSON?

A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.


1 Answers

Might be currently impossible.

This because Jackson currently supports @JacksonUnwrapped for the opposite case, but no @JacksonWrapped

Feature request: https://github.com/FasterXML/jackson-annotations/issues/42

like image 193
usr-local-ΕΨΗΕΛΩΝ Avatar answered Oct 19 '22 03:10

usr-local-ΕΨΗΕΛΩΝ