利用 fastjson 包将 json 字符串转换为 map 对象
json 字符串格式如下所示
{
"one": {
"number": "01",
"text": "序号1"
},
"two": {
"number": "02",
"text": "序号2"
},
"three": {
"number": "03",
"text": "序号3"
}
}
具体实现如下
- 引入依赖包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.11.graal</version>
</dependency>
- 代码处理逻辑
package com.yuhuofei.utils;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
/**
* @Description
* @ClassName HandleJsonData
* @Author yuhuofei
* @Date 2022/8/17 21:23
* @Version 1.0
*/
public class HandleJsonDataUtil {
public static void jsonSwitchToMap(String data) {
System.out.println("得到的json数据:\n" + data);
//json转为map
Map map = JSONObject.parseObject(data, Map.class);
//使用entrySet方式
for (Object entrySetOj : map.entrySet()) {
System.out.println("使用entrySet方式得到的key是:" + ((Map.Entry) entrySetOj).getKey() + "," + "value是:" + ((Map.Entry) entrySetOj).getValue());
JSONObject value = JSONObject.parseObject(((Map.Entry) entrySetOj).getValue().toString());
System.out.println("number是:" + value.getString("number") + "," + "text是:" + value.getString("text"));
}
System.out.println();
System.out.println("===================分隔线======================");
System.out.println();
//使用keySet方式
for (Object keySetOj : map.keySet()) {
System.out.println("使用keySet方式得到的key是:" + keySetOj + "," + "value是:" + map.get(keySetOj));
JSONObject value = JSONObject.parseObject(map.get(keySetOj).toString());
System.out.println("number是:" + value.getString("number") + "," + "text是:" + value.getString("text"));
}
}
//测试方法
public static void main(String[] args) {
String jsonData = "{\n" +
" \"one\": {\n" +
" \"number\": \"01\",\n" +
" \"text\": \"序号1\"\n" +
" },\n" +
" \"two\": {\n" +
" \"number\": \"02\",\n" +
" \"text\": \"序号2\"\n" +
" },\n" +
" \"three\": {\n" +
" \"number\": \"03\",\n" +
" \"text\": \"序号3\"\n" +
" }\n" +
"}";
jsonSwitchToMap(jsonData);
}
}
测试结果
版权声明:本文为Crezfikbd原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。