简单记录一下一个fastjson框架和jackson进行序列化的使用案例:
原json字符串:
“{“lockCount”:”{1:790,113:1,2:0,211:0,101:1328,118:8,137:0,301:0,302:0}“,“inventoryCount”:”{1:25062,113:2,2:10000,211:2,101:11034,118:9,137:40,301:903914,302:2070}“}”;
序列化代码:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;String jsonString = "{\"lockCount\":\"{1:790,113:1,2:0,211:0,101:1328,118:8,137:0,301:0,302:0}\",\"inventoryCount\":\"{1:25062,113:2,2:10000,211:2,101:11034,118:9,137:40,301:903914,302:2070}\"}";try {Map<String, String> resultMap = JSON.parseObject(jsonString, new TypeReference<Map<String, String>>() {});// 获取 lockCount 和 inventoryCount 的值String lockCountJson = resultMap.get("lockCount");String inventoryCountJson = resultMap.get("inventoryCount");// 转换为相应的 Map 对象Map<Integer, Integer> lockCountMap = JSON.parseObject(lockCountJson, new TypeReference<Map<Integer, Integer>>() {});Map<Integer, Integer> inventoryCountMap = JSON.parseObject(inventoryCountJson, new TypeReference<Map<Integer, Integer>>() {});System.out.println("lockCountMap: " + lockCountMap);System.out.println("inventoryCountMap: " + inventoryCountMap);} catch (Exception e) {e.printStackTrace();}
结果:
使用Jackson序列化:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;public class JsonToMapExample {public static void main(String[] args) {String jsonString = "{\"lockCount\":\"{1:790,113:1,2:0,211:0,101:1328,118:8,137:0,301:0,302:0}\",\"inventoryCount\":\"{1:25062,113:2,2:10000,211:2,101:11034,118:9,137:40,301:903914,302:2070}\"}";try {ObjectMapper objectMapper = new ObjectMapper();TypeReference<Map<String, String>> typeReference = new TypeReference<Map<String, String>>() {};Map<String, String> resultMap = objectMapper.readValue(jsonString, typeReference);// 获取 lockCount 和 inventoryCount 的值String lockCountJson = resultMap.get("lockCount");String inventoryCountJson = resultMap.get("inventoryCount");// 转换为相应的 Map 对象Map<Integer, Integer> lockCountMap = objectMapper.readValue(lockCountJson, new TypeReference<Map<Integer, Integer>>() {});Map<Integer, Integer> inventoryCountMap = objectMapper.readValue(inventoryCountJson, new TypeReference<Map<Integer, Integer>>() {});System.out.println("lockCountMap: " + lockCountMap);System.out.println("inventoryCountMap: " + inventoryCountMap);} catch (Exception e) {e.printStackTrace();}}
}