0

I have a ServerEndpoint that will be recieving different JSON formats. Since we are only allowed one message handler per message type, my one decoder will have to convert the message to the corresponding Java objects.

In my decoder, I am trying to convert the message recieved to either SubClassA or SubClassB (which implemets the same interface) using the ObjectMapper class. The ObjectMapper class has a readValue method that requires the type I am trying to map the json to and will throw an exception when it cannot convert to the specified type.

I am currently decoding it like the following, but it is not very elegant.

@Override
public Message decode(String message) throws DecodeException {
    ObjectMapper mapper = new ObjectMapper();

    try {
        SubclassA obj = mapper.readValue(message, SubclassA .class);
        return obj;
    } catch (IOException e) {
    }

    try {
        SubclassB obj = mapper.readValue(message, SubclassB .class);
        return obj;
    } catch (IOException e) {
    }

    throw new DecodeException(message, "Failed to decode message.");
}

What is the best way to decode the JSON string into the corresponding Java object using ObjectMapper?

dalawh
  • 886
  • 8
  • 15
  • 37

2 Answers2

3

Use Jackson, you can declare subtypes for the parent object. Your Json will contain @type with with the name of the subtype, look at this post Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

Community
  • 1
  • 1
Vitalii Kravchenko
  • 395
  • 1
  • 2
  • 9
0

Jackson is one of the best options to work with JSON in Java.

For polymorphic deserialization, consider the following:

Community
  • 1
  • 1
cassiomolin
  • 124,154
  • 35
  • 280
  • 359