`
菜鸟级JAVA
  • 浏览: 92763 次
  • 性别: Icon_minigender_1
  • 来自: 湖南
社区版块
存档分类
最新评论

json字符串转map格式

    博客分类:
  • json
阅读更多
直接上代码:
//json字符串转成map
public static Map<String, Object> 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<String, Object> JsonToMap(JsonNode jsonNode) {
        if (jsonNode == null) {
            return null;
        }
        Iterator<String> paramsIterator = jsonNode.getFieldNames();//获得一个迭代器 存储jsonNode的所有key
        Map<String, Object> map = new HashMap<String, Object>();
        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<String, Object> tempMap = JsonToMap(jsonSonNode);//递归调用
                if (tempMap != null) {
                    map.put(paramName, tempMap);
                }
            }  else if (jsonSonNode.isArray()) {//如果是数组
                Iterator<JsonNode> nodeIterator = jsonSonNode.getElements();//获取数组里的值
                ArrayList<Map<String, Object>> tempMaplist = new ArrayList<Map<String, Object>>();
                while (nodeIterator.hasNext()) {
                    JsonNode tempJsonNode = nodeIterator.next();//得到数组里的一个对象
                    Map<String, Object> tempM = JsonToMap(tempJsonNode);//递归调用
                    if (tempM != null) {
                        tempMaplist.add(tempM);
                    }
                }
                map.put(paramName, tempMap);
            }
        }
        return map;
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics