java JSON转换为Array或HashMap-日常笔记

一、需求

由于需要将json存储在influxdb中,为了解析各个key/value所以需要变换成HashMap.

二、所用依赖

Maven:

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0</version>
</dependency>

三、代码

		/**
		 * JSON 转成key,value映射表
		 * @param jsonNode
		 * @param map
		 */
		public static void Json2Map(JsonNode jsonNode, Map<String, String>  map)
		{
			
			Iterator<Entry<String, JsonNode>>  fields = jsonNode.fields();
			
			while(fields.hasNext())
			{
				Entry<String, JsonNode> entry = fields.next();
				
				String key = entry.getKey();
				JsonNode value = entry.getValue();
				// 如果子节点可以迭代,则继续迭代
				if(value.isContainerNode())
				{
					Json2Map(value,map);
				}else{
					map.put(key, value.asText());
				}

			}
		}

使用代码:

JsonNode jsonNode = new ObjectMapper().readTree(msgBody); //msgBody为String json
Map<String, String> map = new HashMap<String, String>();
Json2Map(jsonNode,map);
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
// 迭代添加到influxdb point builder中
while(it.hasNext())
{
	Map.Entry<String, String> entry = it.next();
	pointBuilder.addField(entry.getKey(), entry.getValue());//业务代码
}

例如JSON:

{
    "a": {
        "a1": "43.23",
        "a2": 32.32,
        "a3": 35,
        "a4": {
            "a4-1": 3235
        }
    },
    "b": {
        "b1": 432,
        "b2": "543.23"
    },
    "c1": 443232,
    "d1": "432432.432"
}

迭代后输出:

格式:key=value

a1=43.23
a2=32.32
a3=35
a4-1=3235
b1=432
b2=543.23
c1=443232
d1=432432.432

分享到:更多 ()