简体   繁体   English

使用 Jackson 反序列化 JSON 时去除空格

[英]stripping whitespace when deserializing JSON using Jackson

I have a Dropwizard application with a bunch of APIs which are published.我有一个 Dropwizard 应用程序,其中包含一组已发布的 API。 I need to strip trailing/leading whitespaces as well as carriage returns, tabs, etc. from incoming string values (such as address, names).我需要从传入的字符串值(例如地址、名称)中去除尾随/前导空格以及回车、制表符等。 Rather than going and changing each API implementation and doing so manually, I thought about configuring a JSON deserializer to do so.我没有去更改每个 API 实现并手动执行此操作,而是考虑配置一个 JSON 反序列化器来执行此操作。

I can't seem to find such an option in Jackson.我似乎在杰克逊找不到这样的选择。 Also, even if I create a custom deserializer and find how to register it within the Dropwizard application, it seems that each deserializer is configured per specific class rather than "global".此外,即使我创建了一个自定义反序列化器并找到了如何在 Dropwizard 应用程序中注册它,似乎每个反序列化器都是按特定类而不是“全局”配置的。

My question is whether there is an option in Jackson to configure a GLOBAL deserializer for any java.lang.String property (simple or part of another object) or some sort of global callback method which will allow me to examine and potentially modify a JSON property value.我的问题是 Jackson 中是否有一个选项可以为任何 java.lang.String 属性(简单或另一个对象的一部分)或某种全局回调方法配置 GLOBAL 反序列化器,这将允许我检查并可能修改 JSON 属性价值。

I found a solution.我找到了解决方案。 By implementing a custom JsonDeserializer, you can manipulate values.通过实现自定义 JsonDeserializer,您可以操作值。

public class WhitespaceDeserializer extends JsonDeserializer<String> {
    @Override
        public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        return p.getText().trim();
}

The deserializer then has to be registered with the object mapper:然后必须使用对象映射器注册反序列化器:

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule().addDeserializer(String.class, new WhitespaceDeserializer());
mapper.registerModule(simpleModule);

A little bit more work than I thought - I was hoping there is a simple an existing way of setting a flag somewhere, but this does the trick.比我想象的要多一点工作-我希望有一种简单的现有方法可以在某处设置标志,但这可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM