使用Jackson JSON库,是否可以将自定义对象转换为字符串并接收字符串?

时间:2016-11-11 15:42:25

标签: java json jackson

我想要一个自定义对象,比如MyDate,它只有一个toString方法和一些构造函数,但我希望该对象接受'String'数据并写入字符串数据。

例如,我会有Java代码:

public class MyDate {
 ...
}

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

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

我该如何做到这一点?

1 个答案:

答案 0 :(得分:0)

根据您的评论,您是否建议您从Jackson中的字符串序列化和反序列化MyDate?这可以使用JsonDeserilizer和JsonSerilizer完成。这是一个例子:

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)
    }
}

作为回报(将MyDate消毒为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());

    }
}

然后你需要像这样注释你的根类:

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

这是否涵盖了它?