Berlin Brown Berlin Brown - 28 days ago 6
Java Question

With Jackson JSON library, is it possible to convert custom Objects into a string and receive a string?

I want to have a Custom Object, say MyDate that will only have a toString method and some constructor but I want that object to accept 'String' data and also write string data.

For example, I would have Java code:

public class MyDate {
...
}

public class RootJson {
private MyDate myDate;
private String id;
}

And the the json would be:
{
"myDate": "2015000000",
"id": "2014000aabc"
}


How can I accomplish this?

Answer

Based on your comment, are you suggesting you want to serialize and deserialize MyDate from a String in Jackson? This can be done with JsonDeserilizer and JsonSerilizer. Here is an example:

public class JsonMyDateDeserializer extends JsonDeserializer<MyDate> {

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

        String stringValue = jsonParser.getText();
        // Convert it to a MyDate how ever you want....  just example below
        return new MyDate(stringValue)
    }
}

And to do it in return (sterilize MyDate to JSON):

public class JsonMyDateSerializer extends JsonSerializer<MyDate> {

    @Override
    public void serialize(MyDate myDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        // Just an example....   convert your myDate something the jsonGenerator can handle
        jsonGenerator.writeString(myDate.toString());

    }
}

then you need to annotate your root class like this:

public class RootJson {
    @JsonSerialize(using = JsonMyDateSerializer.class)
    @JsonDeserialize(using = JsonMyDateDeserializer.class)
   private MyDate myDate;
   private String id;
}

Does this cover it?