如何将列表映射到具有列表结构的对象

问题描述 投票:0回答:1

如何使用MapStruct创建将列表(我的源)映射到带有列表(目标)的对象的映射器?

我的源类看起来像这样:

class SourceB {
    private String name;
    private String lastname;
}

class SourceA { 
    private Integer id;
    private List<SourceB> bs;
}

所以我需要将其转换为此:

class DestinationA {
    private Integer id;
    private DestinationAB bs;
}

class DestinationAB {
    private List<DestinationB> b;
}

class DestinationB {
    private String name;
    private String lastname;
}

预期的示例json:

来源:

{
  "id": 1,
  "bs": [
    {
      "name": "name1",
      "lastname": "last1"
    },
    {
      "name": "name2",
      "lastname": "last2"
    }
  ]
}

目的地:

{
  "id": 1,
  "bs": {
    "b": [
      {
        "name": "name1",
        "lastname": "last1"
      },
      {
        "name": "name2",
        "lastname": "last2"
      }
    ]
  }
}

java mapstruct
1个回答
0
投票

非常简单。只需将@Mapping注释和指定的sourcedestination放在映射方法的顶部即可。

@Mapper
public interface SourceMapper {
    @Mapping(source = "bs", target = "bs.b")
    DestinationA sourceAToDestinationA(SourceA sourceA);
}
© www.soinside.com 2019 - 2024. All rights reserved.