@Test public void test() { JsonSerializerFactory factory = new JsonSerializerFactory(); final JsonSerializer jsonSerializer = factory.includeNulls().create(); final String json = jsonSerializer.serialize( Maps.map("job", "programmer", "age", null, "showSize", 12) ).toString(); ok |= json.contains("\"age\":null") || die(); } }
@Test public void testWithMapUsingFactory() { JsonParserFactory jsonParserFactory = new JsonParserFactory() .useFieldsFirst() .lax() //allow loose parsing of JSON like JSON Smart .setCharset( StandardCharsets.UTF_8 ) //Set the standard charset, defaults to UTF_8 .setLazyChop( true ) //similar to chop but only does it after map.get ; JsonSerializerFactory jsonSerializerFactory = new JsonSerializerFactory() .useFieldsFirst() //one of these //.addPropertySerializer( ) customize property output //.addTypeSerializer( ) customize type output .useJsonFormatForDates() //use json dates //.addFilter( ) add a property filter to exclude properties .includeEmpty().includeNulls().includeDefaultValues() //override defaults .handleComplexBackReference() //uses identity map to track complex back reference and avoid them .setHandleSimpleBackReference( true ) //looks for simple back reference for parent .setCacheInstances( true ) //turns on caching for immutable objects ; final ObjectMapper objectMapper = JsonFactory.create(jsonParserFactory, jsonSerializerFactory); MyClass myClass = new MyClass(); final String json = objectMapper.toJson(myClass); puts(json); final MyClass myClass1 = objectMapper.readValue(json, MyClass.class); assertEquals("foo", myClass1.string); assertEquals(1, myClass1.integer); assertNull(myClass1.map); }
public void test3() { user = new User("red", "yellow", "green", "purple"); puts(user.getFavoriteColors()); final JsonParserFactory jsonParserFactory = new JsonParserFactory().usePropertiesFirst().useAnnotations(); final JsonSerializerFactory serializerFactory = new JsonSerializerFactory().includeNulls().useAnnotations(); final ObjectMapper objectMapper = new ObjectMapperImpl(jsonParserFactory, serializerFactory); json = objectMapper.toJson(user); puts(json); user2 = objectMapper.fromJson(json, User.class); puts(user.getFavoriteColors()); ok = user.equals(user2) || die("Users should be equal", user, user2); }
.includeEmpty().includeNulls().includeDefaultValues() //override defaults