Jackson JSON序列化包含仅忽略空字段和空集合

时间:2018-02-23 22:55:49

标签: jackson jackson-modules jackson-databind

我们最近从Jackson json 2.8.2转移到2.9.4,我们看到了行为的重大变化。我们使用的是JDK 1.8。

之前我们在对象映射器级别将Serialization包含设置为NON_DEFAULT,并且所有工作正常。

现在更改为2.9.2之后,NON_DEFAULT忽略了所有默认值,如布尔值false,整数0,......这打破了我们的测试用例。

我们的要求是只忽略空字段和空白字段,如返回[]。

但我们仍然希望不要忽略空字符串,例如test =""

我们尝试了non_empty,non_absent都忽略了每个字段(null,[],"")。

您能否建议我们如何定制序列化行为以满足我们的要求?如果您需要任何进一步的细节,请告诉我。

1 个答案:

答案 0 :(得分:0)

几种方式:

  1. 为类型// NodeJS implementation of crypto, I'm sure google's // cryptoJS would work equally well. var crypto = require('crypto'); // The value stored in [dbo].[AspNetUsers].[PasswordHash] var hashedPwd = "ADOEtXqGCnWCuuc5UOAVIvMVJWjANOA/LoVy0E4XCyUHIfJ7dfSY0Id+uJ20DTtG+A=="; var hashedPasswordBytes = new Buffer(hashedPwd, 'base64'); var hexChar = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]; var saltString = ""; var storedSubKeyString = ""; // build strings of octets for the salt and the stored key for (var i = 1; i < hashedPasswordBytes.length; i++) { if (i > 0 && i <= 16) { saltString += hexChar[(hashedPasswordBytes[i] >> 4) & 0x0f] + hexChar[hashedPasswordBytes[i] & 0x0f] } if (i > 0 && i > 16) { storedSubKeyString += hexChar[(hashedPasswordBytes[i] >> 4) & 0x0f] + hexChar[hashedPasswordBytes[i] & 0x0f]; } } if (storedSubKeyString === '') { return false } // password provided by the user var password = 'welcome1'; // TODO remove debug - logging passwords in prod is considered // tasteless for some odd reason console.log('cleartext: ' + password); console.log('saltString: ' + saltString); console.log('storedSubKeyString: ' + storedSubKeyString); // This is where the magic happens. // If you are doing your own hashing, you can (and maybe should) // perform more iterations of applying the salt and perhaps // use a stronger hash than sha1, but if you want it to work // with the [as of 2015] Microsoft Identity framework, keep // these settings. var nodeCrypto = crypto.pbkdf2Sync(new Buffer(password), new Buffer(saltString, 'hex'), 1000, 256, 'sha1'); // get a hex string of the derived bytes var derivedKeyOctets = nodeCrypto.toString('hex').toUpperCase(); console.log("hex of derived key octets: " + derivedKeyOctets); // The first 64 bytes of the derived key should // match the stored sub key if (derivedKeyOctets.indexOf(storedSubKeyString) === 0) { console.info("passwords match!"); } else { console.warn("passwords DO NOT match!"); } 指定不同的设置:查看String.class;这是ObjectMapper.configOverrides(String.class)的设定者(具有各种工厂方法的类型)。您可以将其设置为JsonInclude.Value(或JsonInclude.Include.NON_NULL),即使默认为其他
  2. 也是如此
  3. ALWAYS注册自定义序列化程序,覆盖/重新定义其String方法,不要将空字符串视为isEmpty(SerializerProvider, String)以排除