I am creating a JSON using Jackson library.
For example I have an Employee with fields: name, surname, and a list of pair of info as showed below
@Data
@NoArgsConstructors
public class EmployeeJSON {
private String name;
private String surname;
private List<CoupleInfo> addresses = new ArrayList<>();
// this class continue with regular implementation to fill the fields and creating an object for CoupleInfo
A class is implemented for CoupleInfo:
@Data
@NoArgsConstructors
public class CoupleInfo {
private List<String> list = new ArrayList<>();
public CoupleInfo(String place, String address){
list.add(place);
list.add(address);
}
}
I would like to get in the JSON, of course with the fields name and surname, the field addresses populated as list of the couple of values (as array in the JSON), but without, inside the array, the field list.
How can do that?
I tried with @JsonIgnore but all the field and the value disappear.
To get this at the end:
{"name":"giulio", "surname":"marri", "addresses":[["roma","piazza liberta'"],["torino","via torre"]]}
instead to be:
{"name":"giulio", "surname":"marri", "addresses":[{"list":["roma","piazza liberta'"]},{"list":["torino","via torre"]}}
CodePudding user response:
you can use @JsonValue to get the addresses as list of lists with no field name:
@Data
@NoArgsConstructor
public class CoupleInfo {
public List<String> list = new ArrayList<>();
public CoupleInfo(String place, String address){
list.add(place);
list.add(address);
}
@JsonValue
public List<String> getList() {
return list;
}
}
the result will be:
{"name":"giulio","surname":"marri","addresses":[["roma","piazza liberta"],["torino","via torre"]]}
