c语言json格式字符串转map,json字符串转map格式

直接上代码:

//json字符串转成map

public static Map StringToMap(String strInput) {

if (strInput == null) {

return null;

}

JsonNode jsonNode = null;

try {

ObjectMapper objectMapper = new ObjectMapper();

jsonNode = objectMapper.readTree(strInput);//将json字符串转成jsonNode

} catch (IOException ex) {

System.out.println("json数据格式异常");

//Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);

return null;

}

return JsonToMap(jsonNode);

}

//jsonNode转成map

public static Map JsonToMap(JsonNode jsonNode) {

if (jsonNode == null) {

return null;

}

Iterator paramsIterator = jsonNode.getFieldNames();//获得一个迭代器 存储jsonNode的所有key

Map map = new HashMap();

while (paramsIterator.hasNext()) {

String paramName = paramsIterator.next();//得到一个key

JsonNode jsonSonNode = jsonNode.get(paramName);

if (jsonSonNode.isInt()) {//如果是int类型数据

map.put(paramName, jsonSonNode.getIntValue());

} else if (jsonSonNode.isLong()) {//如果是long类型数据

map.put(paramName, jsonSonNode.getLongValue());

} else if (jsonSonNode.isTextual()) {//如果是文本

map.put(paramName, jsonSonNode.getValueAsText());

} else if (jsonSonNode.isObject()) {//如果是对象

Map tempMap = JsonToMap(jsonSonNode);//递归调用

if (tempMap != null) {

map.put(paramName, tempMap);

}

}  else if (jsonSonNode.isArray()) {//如果是数组

Iterator nodeIterator = jsonSonNode.getElements();//获取数组里的值

ArrayList> tempMaplist = new ArrayList>();

while (nodeIterator.hasNext()) {

JsonNode tempJsonNode = nodeIterator.next();//得到数组里的一个对象

Map tempM = JsonToMap(tempJsonNode);//递归调用

if (tempM != null) {

tempMaplist.add(tempM);

}

}

map.put(paramName, tempMap);

}

}

return map;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值