[alibaba/fastjson]fastjson支持JSON字符串解析到指定类型的JavaBean时的多余属性么?

2025-11-24 438 views
0

比如JSON: { "a": "123", "b":"456" }解析到JavaBean只有a属性没有b属性,是否提供入口可以回调处理,比如回调抛出异常,说b对应不到JavaBean的任何属性,多谢了。

回答

0

转成json object,remove掉b,再parseobject

6

不是啊,我是想如果JSON字符串有任何多余的属性,我都要抛出异常,拒绝掉。只允许出现JavaBean中定义的属性。

5

我明白你的意思了,是想加个feature,deserialize的时候自动去掉不匹配的key。

6

不是,是相在deserialize,遇到不匹配的key,能给我一个回调接口,我自己处理,比如记录日志,抛出异常等。

5

if (fieldDeser == null) { if (!lexer.isEnabled(Feature.IgnoreNotMatch)) { throw new JSONException("setter not found, class " + clazz.getName() + ", property " + key); }

如果没有此属性,又没有设置Feature.IgnoreNotMatch,会抛出以上异常。

1

I'm adding a new feature to process this case now,just wait for my pr, plz.

7

感谢你的及时处理。我看了一下你的示例,确实是可以定义拦截器,但是我不想在全局上来设置或者取消拦截器,而是在一些特定的解析请求过程中,才需要指定拦截器,不知道你是否方便做成请求级别的拦截器,而不是全局的,谢谢。

0

Feature.IgnoreNotMatch这个特性,不知道在JSON.parseObject(jsonString, BeanType, Features...)上怎么传递,我不想开启Feature.IgnoreNotMatch它,怎么指定?

1

我给你的示例是放到全局ParserConfig的, 你可以每次解析的时候,在JSON.parseObject的参数里传递自己的ParserConfig,以达到只控制部分拦截的功能。

如果parseObject时没有传递feature和config,使用一个默认的ParserConfig.global,其自带如下参数:

static {
        int features = 0;
        features |= Feature.AutoCloseSource.getMask();
        features |= Feature.InternFieldNames.getMask();
        features |= Feature.UseBigDecimal.getMask();
        features |= Feature.AllowUnQuotedFieldNames.getMask();
        features |= Feature.AllowSingleQuotes.getMask();
        features |= Feature.AllowArbitraryCommas.getMask();
        features |= Feature.SortFeidFastMatch.getMask();
        features |= Feature.IgnoreNotMatch.getMask();
        DEFAULT_PARSER_FEATURE = features;
    }

其中IgnoreNotMatch已经包含了,你可以自己new一个ParserConfig,配置自己的参数,传递给JSON.parseObject方法,当然这时候你也可以new一个NotMatchIntercepter给自定义的ParserConfig。

1

谢谢,这个就是我想要的功能。