有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Mapstruct从源对象的一组字段中准备一个列表,并将其设置为目标对象

我将从mongo db文档中获得以下平面结构作为源对象,我需要根据模式对一些字段进行分组,以准备arraylist并将其设置为目标对象

{
   "_id": 1,
   "clientId": "1001",
   "grant1Id": "1",
   "grant1Type" : "A",
   "grant1Amount": "100",
   "grant2Id": "2",
   "grant2Type": "B",
   "grant2Amount": "200",
   "grant3Id": "3",
   "grant3Type": "C",
   "grant3Amount": "300",
   .....so on
}

赠款最多可用于20件物品。所以,我想合并所有的grant字段并准备一个数组

输出应该如下所示:

{
    "_id": 1,
   "clientId": "1001",
   "grants": [
    {
     "grantId": "1",
     "grantType" : "A",
     "grantAmount": "100",
    },
    {      
     "grantId": "2",
     "grantType" : "B",
     "grantAmount": "200",
    },
    {
     "grantId": "3",
     "grantType" : "C",
     "grantAmount": "300",
    }
   ]
}

源对象结构:

public class Source {
      private String id;
      private String clientId;
      private String grant1Id;
      private String grant1Type;
      private String grant1Amount;
      ...so on
}

目标对象:

public class Target {
      private String id;
      private String clientId;
      private List<Grant> grants;
}

任何帮助都将不胜感激

谢谢


共 (1) 个答案

  1. # 1 楼答案

    您可以使用afterMapping方法来设置目标对象

        @AfterMapping
        default void convertNameToUpperCase(Source source, @MappingTarget Target target) {
            //set grants from source to target
        }