Deserializing json to java objects (but not all of it)

This post is about deserializing using Java and JAX-RS (Jersey) when you have a piece of json that’s amorphous (not well defined)

You have some json that generally looks like this

{
  id: 1
  config: {
    foo: "lalala"
  }
}

But the “config” is actually amorphous, so it might also look like this

{
  id: 1
  config: {
    bar: 15
  }
}

So you build a REST API like this

@POST
@Path("/api")
public void doStuff(Thing thing) {
  ...
}

And what does “Thing” look like?

class Thing {
  public int id;
  public ??? config;
}

How do you define config? Is it a class with foo or bar?
I needed to keep it as a string, since I’m just storing it in the database.

So let’s write it as

  public String config;

But this won’t work. You’ll likely get an error like this

Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@6ed35c92; line: 1, column: 39] (through reference chain: Thing["config"])

You will need to write a Deserializer for it like this

import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

public class KeepAsJsonDeserialzier extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {

        TreeNode tree = jp.getCodec().readTree(jp);
        return tree.toString();
    }
}

Credit goes to StackOverflow

And then annotate the field or setter method with this

  @JsonDeserialize(using=KeepAsJsonDeserializer.class)
  public String config;
Advertisements
Tagged , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: