使用 Jackson ObjectMapper 反序列化或序列化任何类型的对象并处理异常 [英] Deserializing or serializing any type of object using Jackson ObjectMapper and handling exceptions

查看:31
本文介绍了使用 Jackson ObjectMapper 反序列化或序列化任何类型的对象并处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I currently have this code I am trying to refactor in order to allow for more possible class types (simplified with dummy code, but the gist is the same):

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.有没有更好的方法来做到这一点,而不必将所有内容更改为 Object 而不是 SomeSpecificClass?这样我们就可以在 deserializeSomething 中返回正确的类型(并且不必在我们从调用者那里得到返回值后转换它)?

We recently found out that we will probably have to accept other types here, not just SomeSpecificClass. Is there a better way of doing this without having to change everything to Object instead of SomeSpecificClass? So that we can return the right type in deserializeSomething (and not have to cast it after we get the return value from the caller)?

推荐答案

从示例实现开始:

class JsonObjectConverter {

    private ObjectMapper mapper = new ObjectMapper();

    public String serialiseToJson(Object value) {
        try {
            return mapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Could not serialise: " + value, e);
        }
    }

    public <T> T deserialiseFromJson(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (IOException e) {
            throw new IllegalArgumentException("Could not deserialize: " + clazz, e);
        }
    }

    public SomeSpecificClass deserialiseToSomeSpecificClass(String json) {
        return deserialiseFromJson(json, SomeSpecificClass.class);
    }
}

您可以编写两个通用方法:serialiseToJsondeserialiseFromJson,它们可以将任何类型序列化为 JSON 和反序列化 JSON 负载到给定的 Class.您当然可以为最常见和最常用的类实现一些额外的方法,例如 deserialiseToSomeSpecificClass.您可以按照以下格式编写任意数量的方法:deserialiseToXYZ.

You can write two general methods: serialiseToJson and deserialiseFromJson which can serialise any type to JSON and deserialise JSON payload to given Class. You can implement of course some extra methods for most common and most used classes like deserialiseToSomeSpecificClass. You can write as many method as you need in this format: deserialiseToXYZ.

这篇关于使用 Jackson ObjectMapper 反序列化或序列化任何类型的对象并处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆