Different JSON serialization for the same class

Common problem: the class I want to serialize in two different ways. In one case, I want to include the output of the method getItems(), and in the other case, I do not want to see this in the output.

Choose to use Jackson Views, as this gives me maximum flexibility. Created:

public class Views {
    public static class WithOrderItems {
    }
}

Then in the class to be serialized:

@JsonView(Views.WithOrderItems.class)
public Iterable<OrderItem> getItems() {
    //Code...
}

In the serialization method:

// Expectation: this *should not* include "items" in JSON output
mapper.writeValueAsString(retObj)

returns the same as:

// Expectation: this should include "items" in JSON output
mapper.writerWithView(Views.WithOrderItems.class).writeValueAsString(retObj)

In both cases, the entire object is serialized (it is as if the View were ignored). Why is this happening?

, .. Jackson. - , ? , , , mapper.

My mapper:

public static ObjectMapper mapper = new ObjectMapper().registerModule(new GuavaModule())
            .registerModule(MoneySerializer.getAsModule());

static {
    mapper.setSerializationInclusion(Include.NON_ABSENT);
}

(getAsModule() . MoneySerializer Joda Money .)

, , , .

:

  • : 2.6.1
  • Java 7
  • GAE SDK 1.9.30
  • Objectify 5.1.7
+4
2

, , , .

, . , mapper .

. " ", , "" - , . "" , Object.class.

+1

@ghokun...

, "items" (, , /, ), :

mapper.writerWithView(Object.class)

"items" (, , /, Views.WithOrderItems), :

mapper.writerWithView(Views.WithOrderItems.class)

mapper (.. ObjectWriter, mapper.writerWithView(...)) .

+2

Source: https://habr.com/ru/post/1619442/


All Articles