猿问

使用 Jackson ObjectMapper 反序列化或序列化任何类型的对象并处理异常

我目前有这段代码,我正在尝试重构以允许更多可能的类类型(使用虚拟代码进行了简化,但要点是相同的):


private String serializeSomething(final SomeSpecificClass something) {

    try {

        return mapper.writeValueAsString(someething);

    } catch (final IOException e) {

        throw new SomeCustomException("blah", e);

    }

}


private SomeSpecificClass deserializeSomething(final String payload) {

    try {

        return mapper.readValue(payload, SomeSpecificClass.class);

    } catch (final IOException e) {

        // do special things here

        throw new SomeCustomException("blah", e);

    }

}

我们最近发现我们可能不得不在这里接受其他类型,而不仅仅是SomeSpecificClass. 有没有更好的方法可以做到这一点而不必将所有内容更改为Objectinstead of SomeSpecificClass?这样我们就可以返回正确的类型deserializeSomething(而不必在我们从调用者那里获得返回值后强制转换它)?


白板的微信
浏览 108回答 1
1回答

炎炎设计

从示例实现开始:class JsonObjectConverter {&nbsp; &nbsp; private ObjectMapper mapper = new ObjectMapper();&nbsp; &nbsp; public String serialiseToJson(Object value) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return mapper.writeValueAsString(value);&nbsp; &nbsp; &nbsp; &nbsp; } catch (JsonProcessingException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new IllegalArgumentException("Could not serialise: " + value, e);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public <T> T deserialiseFromJson(String json, Class<T> clazz) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return mapper.readValue(json, clazz);&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new IllegalArgumentException("Could not deserialize: " + clazz, e);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public SomeSpecificClass deserialiseToSomeSpecificClass(String json) {&nbsp; &nbsp; &nbsp; &nbsp; return deserialiseFromJson(json, SomeSpecificClass.class);&nbsp; &nbsp; }}您可以编写两种通用方法:serialiseToJson和deserialiseFromJson可以将任何类型JSON序列化为 并将JSON有效负载反序列化为给定的Class。您当然可以为最常见和最常用的类实现一些额外的方法,例如deserialiseToSomeSpecificClass. 您可以按照以下格式编写任意数量的方法:deserialiseToXYZ.
随时随地看视频慕课网APP

相关分类

Java
我要回答