Map与JSONObject对象相互转换记录
发布日期:2025-04-12 00:41:44 浏览次数:12 分类:精选文章

本文共 1446 字,大约阅读时间需要 4 分钟。

业务背景:由于需要嵌套一些数据报表,页面点击菜单直接进行URL访问,鉴于访问权限受限,后台需要修改URL权限并返回JSON数据以防止异常。为此,后台进行了对JSON对象与Map的转换,以下是具体实现方法。

配置JSON文件格式:

{    "redashLinks": [        {            "name": "盈利表",            "url": "http://ip/public/dashboards/share/fQUPgt8oLyuunojAEVUzsGn8G9bOYVNFl2KuZzsv"        },        {            "name": "亏损表",            "url": "http://ip/public/dashboards/share/qDsDeOM0JMomy3ZgCEhxnPYWgzCpiMp93KfYRvhT"        }    ]}

将获取到的JSON数据转换处理:

  • 首先将JSON对象转换为Map:
  • Map
    jsonStrToMap(JSONObject json) { Map
    data = new HashMap<>(); String apiKey = getApiKey(); Iterator
    > it = json.entrySet().iterator(); while (it.hasNext()) { Map.Entry
    entry = it.next(); List
    > list = (List
    >) entry.getValue(); for (Map
    map : list) { StringBuffer str = new StringBuffer(); str.append(map.get("url")); str.append("?key="); str.append(apiKey); data.put(map.get("name"), str.toString()); } } return data;}
    1. 将返回的Map转回JSONObject:
    2. ObjectMapper mapper = new ObjectMapper();String writeValueAsString = mapper.writeValueAsString(jsonMap);JSONObject.parseObject(writeValueAsString);

      技术依赖:

      com.fasterxml.jackson.core
      jackson-databind
      2.9.8
      compile
      com.alibaba
      fastjson
      1.2.7

      以上方法实现了对JSON数据的转换和URL权限的处理,确保了数据的安全性和灵活性。

    上一篇:Map中key和value值是否可以为null或空字符串?
    下一篇:MapXtreme 2005 学习心得 画道路区域(十二)

    发表评论

    最新留言

    路过,博主的博客真漂亮。。
    [***.116.15.85]2025年05月13日 07时10分23秒