0

Introduction

I need to serialize a java object (Fahrweg) that contains nested objects (all implement the interface FahrwegEreignis) to json. My code to do this is as follows:

Fahrweg fahrweg = new Fahrweg();

ObjectMapper mapper = new ObjectMapper();

mapper.addMixIn(FahrwegEreignis.class, FahrwegEreignisMixIn.class);

ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();

try {
  String json = ow.writeValueAsString(fahrweg);
  System.out.print(json);
} catch (JsonProcessingException e) {
  e.printStackTrace();
}

By default, the type of the object is not contained in the resulting json (I assume because JS is dynamically typed).

I would like to add a field to every object about like so: "type" : "classname".

I've read about the Jackson annotations, and I'm using mixin because I cannot modify the classes in question. My mixin interface (FahrwegEreignisMixIn) looks like this:

import com.fasterxml.jackson.annotation.JsonProperty;

public interface FahrwegEreignisMixIn {
    @JsonProperty("type")
    //TODO
}

Question

What do I need to put at //TODO?

My first instinct was Class<?> getClass(); but that doesn't work.

Answer

The answer in the duplicate question worked for me. I had to change my FahrwegEreignisMixIn to this:

import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "type")
public interface FahrwegEreignisMixIn {}
Marius Schär
  • 336
  • 2
  • 17

2 Answers2

0

Have you considered using Google GSon? Works like a charm for me.

Your code would probably look like so:

FahrwegEreignis fahrweg = new Fahrweg();
Gson gson = new Gson();
String json = gson.toJson(fahrweg);
KoenVE
  • 301
  • 2
  • 11
0

You can run the following on the instance of the class that implements an interface:

FahrwegEreignisMixInImpl.getClass().getName()
aviad
  • 8,229
  • 9
  • 50
  • 98