简体   繁体   中英

How to write flattening List deserializer with Jackson?

I'm trying to deserialize JSONs of specific structure into Java classes with Jackson. I have several classes like these:

class A {
  private int number1;
  private List<X> list1;
  private int number2;
}

class X {
  private String field1;
  private double value1;
}


class B {
  private String name2;
  private List<Y> list2;
}

class Y {
  private String field2;
}

And I get JSONs from external system like below:

{
  "number1": 1,
  "list1": {
    "elements": [{
      "field1": "Field 1 value 1",
      "value1": 2.2
    }, {
      "field1": "Field 1 value 2"
    }]
  },
  "number2": 2,
}


{
  "name2": "Name 2",
  "list2": {
    "elements": [{
      "field2": "Field 2 value 1"
    }]
  }
}

All I want is to write a custom deserializer, which could get rid of this elements level in a generic way (I mean to have one deserializer for all classes). Is there any simple way to extend a StdDeserializer to accomplish that or a I have to write a whole new deserializer with my custom algorithm?

You can take a look on this question: Jackson - deserialize inner list of objects to list of one higher level which is very similar. I have implemented there custom deserialiser which can be used for many different types with inner list. Your example POJO could look like this:

class A {
    private int number1;

    @JsonDeserialize(using = InnerListDeserializer.class)
    private List<X> list1;
    private int number2;

    // getters, setters
}

EDIT
If you do not want to use any annotation or custom deserialisation you need to create POJO structure which fit given JSON . You need to create middle POJO :

class ListWrapper<T> {

    private List<T> elements;

    // getter, setter, toString, etc
}

Now, you need to update classes A and B in this way:

class A {
    private int number1;
    private ListWrapper<X> list1;
    private int number2;

    // getters, setters, toString
}

and

class B {

    private String name2;
    private ListWrapper<Y> list2;

    // getters, setters, toString
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM