java中将Map集合转成json格式的数据

本文介绍如何在Java中将Map集合转换成JSON格式的数据。通过引入相关工具包,可以方便地实现Map到JSON的转换,并展示了具体的转换代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们需要加载jar包或者直接使用maven管理中导入以下工具包

 <!--map转换json-->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.7.0</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>net.sf.ezmorph</groupId>
            <artifactId>ezmorph</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

转换的代码:

//创建一个map集合的对象
Map<String, Object> map = new HashMap<String, Object>();
        map.put("msg_id","1234");
        map.put("lib_id",1);
        map.put("img_id", "a975b317-5e20-488b-a67f-050147983c09");
        //将map集合中的数据抓换成json格式
        JSONObject jsonMap = JSONObject.fromObject(map);
        System.out.print("打印转换的数据:"+" "+jsonMap)

在这里插入图片描述
为了方便看数据直接打印出来把数据,Map集合中的键值对数据直接都是使用 “=” 号进行连接的
json数据都是 “:” 连接的
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值