alibaba / fastjson

FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
Apache License 2.0
25.74k stars 6.5k forks source link

Is there a way to register a fieldname aside from a @JSONField annotation? #3577

Open DarthHater opened 3 years ago

DarthHater commented 3 years ago

Hello there!

We've been working with fastjson to try and do something a bit "abstract" with a project. In our JSON we have:

vulnerabilities field, that we want to serialize into a Extension.class.

What we are trying to avoid is on our POJO putting a @JSONField annotation that ties it directly to vulnerability, as we know that more keys will be added (we are attempting to deserialize specific keys into a Map<String, Extension>.

I have yet to find a way with ParserConfig to map a field name to a specific Deserializer. Is this possible? Is there some way to do this? Scratching my head a bit, to be honest. If my description isn't clear let me know!

DarthHater commented 3 years ago

I found a slightly interesting workaround, but have not been able to FULLY get it to work.

I discovered alternateNames which works, but doesn't fully fix our problem because we want to know the actual fieldName it encounters, and a deserializer doesn't seem to be told that, just the "name" of the field so:

    @JSONField(deserializeUsing = ExtensionDeserializer.class, alternateNames = {"vulnerabilities"})
    private Map<String, Extension> extensions;

And in the ExtensionDeserializer, we get fieldName as extensions. We want it as vulnerabilities so that we can place the deserialized contents in a Map<String, Extension>.

DarthHater commented 3 years ago

Something that would be nice is if with ParserConfig we could put a deserializer for a fieldname, because then we could initialize the deserializer with enough context to know the original fieldname.