jackson-dataformat-csv icon indicating copy to clipboard operation
jackson-dataformat-csv copied to clipboard

Null value ignored for unwrapped objects

Open mafor opened this issue 8 years ago • 1 comments

Hi. I have faced a minor issue when using JsonUnwrapped annotation together with a custom null value: null value is ignored when serializing nested objects. Here comes an example:

import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

class Inner {
    public String f1;
    public String f2;
    public String f3;
}

class Outer {
    public String f1;
    @JsonUnwrapped
    public Inner f2;
}

public class Test {

    public static void main(String args[]) throws JsonProcessingException {

        final CsvMapper mapper = new CsvMapper();

        // Set null value to 'null'
        final CsvSchema schema = mapper.schemaFor(Outer.class).withNullValue("null");

        // Create an object. All the fields are NULLs
        final Outer outer = new Outer();

        // Serialize the object.
        // I would expect: null,null,null,null
        // I get: null,,,
        System.out.println(mapper.writer(schema).writeValueAsString(outer));
    }
}

mafor avatar Jun 16 '16 10:06 mafor

I added a test to show what causes the problem, and noticed that Inner f2 was left as null. This is why no writes for enclosing entries occurs: there is nothing to de-reference and in a way nothing to write (in JSON the whole entry would be ignored). So omission of "null" is because no writes exist. You could solve the case here by initializing Inner to be an actual instance, if empty one.

However... this leads to question of what to do with "missing" values -- should those be written as null values, or just omitted? This question is more general than unwrapping (handling of which can not be changed much at any rate), since it is possible to omit writing of any columns: but if so, should filler value of null value be used or not?

My leaning is that filler should indeed be used, but based on past experience suspect that doing that may make some users unhappy (since at this point nothing is written, so there may be use cases where this difference between explicit null write vs missing write could work the way user wants).

So, at very least change to force "null" writing needs to get in 2.9 and not in earlier patches. Whether a new property of CsvSchema is needed, or, possibly, CsvGenerator.Feature, I don't know. It would probably make more sense as CsvGenerator.Feature just to avoid feature creep for schemas.

cowtowncoder avatar Aug 19 '16 22:08 cowtowncoder