首页 > 解决方案 > 映射基本 POJOS 的 ModelMapper 问题

问题描述

我有 2 个用于构建 json 对象的基本 POJO:

public class ProductCreateRequestModel {
    private String name;
    private double price;
    private int qty;
    private String imgPath;

    private CategoryRequestCreateProductModel category;
}

public class CategoryRequestCreateProductModel {
    private String name;
    private String categoryKeyId;
}

基本上它允许我使用像这样的简单 json:

{
    "name": "Pizza,
    "price": 344.0,
    "qty": 15,
    "imgPath": "new/pathImage",
    "category": {
        "categoryKeyId": "23ume70Fu6yqyGUWfQkW110P4ko3gZ",
        "name": "Starter"
    }
}

我想发送这个 JSON 并持久化数据,我期望一个对象作为回报,我用这个 POJO 构建:

public class ProductRest {

    private String productKeyId;
    private String name;
    private double price;
    private int qty;
    private String imgPath;

    private CategoryRest category;
}

在我的控制器中,我只需要调用一个使用 PostMapping 的方法

@PostMapping(
        consumes = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE },
        produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }
)
public ProductRest createProduct(@RequestBody ProductCreateRequestModel productCreateRequestModel) throws Exception {
    ProductRest returnValue = new ProductRest();
    if(productCreateRequestModel.getName().isEmpty() || productCreateRequestModel.getPrice() <= 0)
        throw new ApplicationServiceException(ErrorMessages.MISSING_REQUIRED_FIELDS.getErrorMessage());

    ModelMapper modelMapper = new ModelMapper();
    ProductDto productDto = modelMapper.map(productCreateRequestModel, ProductDto.class);

    ProductDto createdProduct = productService.createProduct(productDto);
    returnValue = modelMapper.map(createdProduct, ProductRest.class);

    return returnValue;
}

我的服务层实际上并没有做任何特别的事情:

@Override
public ProductDto createProduct(ProductDto productDto) {
    return productDto;
}

我的 DTO 层包含以下字段:

@Getter @Setter
public class ProductDto implements Serializable {
    // ommit this member and do not generate getter / setter
    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private static final long serialVersionUID = 1L;

    private Long id;
    private String productKeyId;
    private String name;
    private double price;
    private int availableQty;
    private String imgPath;

    private CategoryDto category = new CategoryDto();
}


@Getter @Setter
public class CategoryDto implements Serializable {
    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private static final long serialVersionUID = 1L;

    private long id;
    private String categoryKeyId;
    private String name;

    private CategoryDto parentCategory;
    private List<CategoryDto> subCategories;

    private String parentCategoryKeyId;

    private Long parentCategoryId;
}

在尝试运行此基本代码时,我收到一条错误消息:

java.lang.NumberFormatException:对于输入字符串:“23ume70Fu6yqyGUWfQkW110P4ko3gZ”

标签: springdtomodelmapper

解决方案


推荐阅读