Parsing CSV with Jackson to POJO with nested POJO fields

181 views Asked by At

Not A Duplicate: How to serialize nested collection of objects with Jackson

My question was immediately closed after somebody left a comment within 49 seconds, so please don't continuously bot-close questions that are not duplicates. The above is for serialization, not deserialization, which to my knowledge Jackson handles differently.

Content:

I have POJO(s) with the following definition(s):

public class SomePojo {
  public String name;
  public int type;
  public OtherPojo ref;
}


public class OtherPojo {
  public int x, y, z;
}

And a CSV containing data in the form:

name,type, x, y, z
foo,1,0.3,1.1,-0.5
bar,5,7.3,-0.1,1.5

Typically with Jackson I've only mapped a 1:1 (meaning each field went to a single column), but is it possible to tell the CsvSchema or the CsvMapper to treat a range of fields as a nested POJO for the type being read?

2

There are 2 answers

0
Vinith_jk_bro On

Yes, you should be able to do this by defining a custom csvSchema for your CSV mapping

0
EmelK On

Add @JsonUnwrapped annotation to OtherPojo ref. This annotation is used to indicate that a property should be serialized "unwrapped".

This would normally be serialized as follows (assuming @JsonUnwrapped had no effect):

  {
    "name" : "foo",
    "type" : 1,
    "ref" : {
      "x" : 0.3,
      "y" : 1.1,
      "z" : -0.5
    }
  }

With @JsonUnwrapped can be changed to this:

    {
        "name" : "foo",
        "type" : 1,
        "x" : 0.3,
        "y" : 1.1,
        "z" : -0.5
    }

For more detailed information please refer to documentation