skip to Main Content

I’m using Jackson in my Java application to serialize objects that contain lists of a known type. However, Jackson is adding an @class attribute to each item in the list, which I want to omit. Here’s an example of the JSON output:

[
  {
    "@class": "com.example.model.Resource",
    "id": "Resource_1",
    "version": 0,
    "reference": false,
    "items": [
      {
        "@class": "com.example.model.Item", // I want to remove this
        "id": "Item01",
        "version": 0,
        "status": "ACTIVE",
        "index": 1,
        "url": "https://example.com/item/1"
      },
      {
        "@class": "com.example.model.Item", // I want to remove this
        "id": "Item02",
        "version": 0,
        "status": "ACTIVE",
        "index": 2,
        "url": "https://example.com/item/2"
      }
    ]
  }
]

Since the type of the items in the list is already known (Item), the @class attribute is redundant. How can I configure Jackson’s ObjectMapper to prevent it from adding the @class attribute to list elements when their type is known?

Additional Info:

I’m using polymorphic type handling elsewhere in my application, so I can’t disable it globally.
I only want to suppress the @class attribute for specific lists where the type is explicit.

Disabling Default Typing: I considered disabling default typing globally using mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);, but I can’t do this because I’m using polymorphic type handling elsewhere in the application.

2

Answers


  1. Jackson have no way to tell that you don’t have child classes for com.example.model.Item. So what you want is impossible.

    Login or Signup to reply.
  2. The @class attribute appears when serializing objects with Jackson if you have specified the @JsonTypeInfo annotation for the classes of objects being serialized. You just need to remove this annotation to get rid of the attribute.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search