Search code examples
javajsonjacksonjackson-databind

How to unwrap object into a list when deserializing


I'm trying to create json that looks like this

"entries" : [
    {
    "name" : <name>,
    "dataPoint" : [
          [long, double],
          [long, double],
        ]
    }
 ]

Each data point is a 2-element array of a long and a double

If I have this

public class Entry {
   private String name;
   private List<DataPoint> dataPoint;

  <constructor and getters omitted>
}

public class DataPoint{
    List<?> data;

    public DataPoint(long date, double counts) {
        this.data = List.of(date, counts);
    }

    public List<?> getDataPoint() {
        return data;
    }
}

I end up with an entry looking like this

{
"name" : "20070480",
"data" : [ {
      "dataPoint" : [ 1681792679186, 1096.0 ]
      }, {
      "dataPoint" : [ 1681792680186, 1147.0 ]
      }
}

@JsonUnwrapped doesn't seem to do anything and I'm not sure that's what I want anyway. I don't want to unwrap it. But instead, I want to wrap the fields as a list, instead of being contained in an object

whereas I want it to look like this

{
"name" : "20070480",
"dataPoint" : [ 
       [ 1681792679186, 1096.0 ]
       [ 1681792680186, 1147.0 ]
}

Is there any way to do this without writing my own serializer?


Solution

  • Just annotate data (or its getter) with @JsonValue:

    @JsonValue
    List<?> data;
    

    This tells the serializer to treat data as the sole representation of this rather than as a property in a JSON object.