一、前言
关于Hadoop的Tools工具类中org.apache.hadoop.fs.azure.security.JsonUtils,将JSON字符串转换Map数据类型,下面通过具体示例进行说明。
二、源码示例
1.org.apache.hadoop.fs.azure.security.JsonUtils源码
package org.apache.hadoop.fs.azure.security;@b@@b@import com.fasterxml.jackson.databind.ObjectMapper;@b@import org.slf4j.Logger;@b@import org.slf4j.LoggerFactory;@b@@b@import java.io.IOException;@b@import java.util.Locale;@b@import java.util.Map;@b@@b@ @b@public final class JsonUtils {@b@ public static final Logger LOG = LoggerFactory.getLogger(JsonUtils.class);@b@@b@ private JsonUtils() {@b@ }@b@@b@ public static Map<?, ?> parse(final String jsonString) throws IOException {@b@ try {@b@ ObjectMapper mapper = new ObjectMapper();@b@ return mapper.readerFor(Map.class).readValue(jsonString);@b@ } catch (Exception e) {@b@ LOG.debug("JSON Parsing exception: {} while parsing {}", e.getMessage(),@b@ jsonString);@b@ if (jsonString.toLowerCase(Locale.ENGLISH).contains("server error")) {@b@ LOG.error(@b@ "Internal Server Error was encountered while making a request");@b@ }@b@ throw new IOException("JSON Parsing Error: " + e.getMessage(), e);@b@ }@b@ }@b@}
2.测试示例代码
package com.xwood.test;@b@@b@import com.fasterxml.jackson.databind.ObjectMapper;@b@import org.slf4j.Logger;@b@import org.slf4j.LoggerFactory;@b@@b@import java.io.IOException;@b@import java.util.Locale;@b@import java.util.Map;@b@@b@public class JsonUtils {@b@ @b@ public static final Logger LOG = LoggerFactory.getLogger(JsonUtils.class);@b@@b@ private JsonUtils() {}@b@@b@ public static Map<?, ?> parse(final String jsonString) throws IOException {@b@ try {@b@ ObjectMapper mapper = new ObjectMapper();@b@ return mapper.reader(Map.class).readValue(jsonString);@b@ } catch (Exception e) {@b@ LOG.debug("JSON Parsing exception: {} while parsing {}", e.getMessage(),@b@ jsonString);@b@ if (jsonString.toLowerCase(Locale.ENGLISH).contains("server error")) {@b@ LOG.error(@b@ "Internal Server Error was encountered while making a request");@b@ }@b@ throw new IOException("JSON Parsing Error: " + e.getMessage(), e);@b@ }@b@ }@b@@b@ public static void main(String[] args) throws Exception {@b@ System.out.println(JsonUtils.parse("{\"key\":\"111\",\"value\":\"222\"}"));@b@ }@b@@b@}
控制台结果
{key=111, value=222}