如何使用MapStruct将String转换为Map? [英] How can I convert String to Map using MapStruct?

查看:87
本文介绍了如何使用MapStruct将String转换为Map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Spring Boot应用程序中有 Story 实体.它具有 String 字段 storyInfo ,其中包含:

I have Story entity in my Spring Boot application. It has String field storyInfo which contains:

{"title":"random title", "description":"random description"}

对于我的 Story 实体,我有 StoryDTO map 字段,称为 storyInfo .问题是:如何使用 MapStruct ?

For my Story entity I have StoryDTO with map field called storyInfo. The question is: how can I convert String field from Strory into Map in StoryDTO using MapStruct?

推荐答案

谢谢大家的回答.通过向MapStruct的 StoryMapper 界面添加一些手动映射器,为我找到了最简单的解决方案.

Thank you guys for answers. Found the easiest solution for me by adding few manual mappers to MapStruct's StoryMapper interface.

// Manual convert to Map
default Map toMap(String text){
    Map map = new HashMap();
    try {
        map = new ObjectMapper().readValue(text, new TypeReference<Map<String, String>>(){});
    } catch (IOException e) {
        e.printStackTrace();
    }

    return map;
}

// Manual convery from map
default String fromMap(Map map){
    return new JSONObject(map).toString();
}

这篇关于如何使用MapStruct将String转换为Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆