包含JSONObject和JSONArray的json字符串进行递归取值,附源码(一)

包含JSONObject和JSONArray的json字符串进行递归取值,附源码(一)

  • 问题背景
  • JSON字符串出参递归
  • 代码测试
  • 总结
  • Lyric: 我们笑得很甜

问题背景

最近做一个项目,整个项目里面都是递归取参数,组装参数,粗滤算了一下有20个左右的递归,简直把我一辈子的递归写够了
注意事项:

  • 可以复制文章的代码自己创建工程,也可以下载源码进行参考

JSON字符串出参递归

1 如果字符串数据时这样的,需要把所有的key和value解析出来,使用List>进行存储

{
	"data": [{
		"msg": "成功",
		"status": "300",
		"data": {
			"records": [{
				"coder": "6d5",
				"name": "yuan",
				"type": "0001"
			}],
			"page_info": {
				"total": 1,
				"page_no": 1,
				"page_size": 1
			}
		}
	}],
	"code": "200",
	"globalId": "df666"
}

2 pom依赖引入


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.6.6version>
        <relativePath/> 
    parent>
    <groupId>com.yggroupId>
    <artifactId>recurseJsonartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>recurseJsonname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.62version>
        dependency>
        <dependency>
            <groupId>com.google.guavagroupId>
            <artifactId>guavaartifactId>
            <version>31.0.1-jreversion>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombokgroupId>
                            <artifactId>lombokartifactId>
                        exclude>
                    excludes>
                configuration>
            plugin>
        plugins>
    build>

project>

3 递归解析json字符串,以及测试main

package com.yg.recursejson.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yg.recursejson.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author suolong
 * @Date 2022/4/1 11:48
 * @Version 1.5
 */
@Service
@Slf4j
public class RecurseService {


    //递归取key和value,jsonObject表示datas中每一个对象
    //taskInputMap存放每一个jsonObject解析出来的key和value
    private void recurseParseJsonObject(JSONObject jsonObject, HashMap<String, Object> taskInputMap) {
        Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            //如果value类型为Map,那么说明又是一个jsonObject对象,因此需要继续递归
            if (entry.getValue() instanceof Map) {
                jsonObject = JSON.parseObject(JSON.toJSONString(entry.getValue()));
                recurseParseJsonObject(jsonObject, taskInputMap);
            }
            //如果value类型为List,说明是一个JSONArray,那么使用for循环把里面的每一个jsonObject对象再一次做递归
            else if (entry.getValue() instanceof List) {
                List<JSONObject> jsonList = JsonUtils.jsonToList(JSON.toJSONString(entry.getValue()), JSONObject.class);
                for (JSONObject json : jsonList) {
                    recurseParseJsonObject(json, taskInputMap);
                }
            } else {
                //说明value是一个普通的属性,String,Number
                taskInputMap.put(entry.getKey(), entry.getValue());
            }
        }
    }


    private void saveTaskInputParam(List<JSONObject> datas, List<HashMap<String, Object>> outputList) {
        log.info(("Begin saveTaskInputParam"));
        for (int i = 0; i < datas.size(); i++) {
            HashMap<String, Object> taskInputMap = Maps.newHashMap();
            JSONObject jsonObject = datas.get(i);
            if (jsonObject == null || jsonObject.isEmpty()) {
                continue;
            }
            recurseParseJsonObject(jsonObject, taskInputMap);
         //   log.info("taskInputMap: {}", taskInputMap);
            outputList.add(taskInputMap);
        }
    }


    public static void main(String[] args) {
        String jsonStr = "{\"data\":[{\"msg\":\"成功\",\"status\":\"200\",\"data\":{\"records\":[{\"coder\":\"6d5\",\"name\":\"yuan\",\"type\":\"0001\"}],\"page_info\":{\"total\":1,\"page_no\":1,\"page_size\":1}}}],\"code\":\"200\",\"globalId\":\"df666\"}";
        RecurseService recurseService = new RecurseService();
        JSONObject data = JSON.parseObject(jsonStr);
        List<JSONObject> datas = Lists.newArrayList();
        datas.add(data);
        List<HashMap<String, Object>> outputList = Lists.newArrayList();
        recurseService.saveTaskInputParam(datas, outputList);
        System.out.println(outputList);
    }
}

4 JsonUtils工具类

package com.yg.recursejson.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Slf4j
public final class JsonUtils {
    /**
     * 定义jackson对象
     */
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     * 

Title: pojoToJson

*

Description:

* * @param data * @return */
public static String objectToJson(Object data) { try { return MAPPER.writeValueAsString(data); } catch (JsonProcessingException e) { log.error("JSON Exception", e); } return null; } /** * 将json结果集转化为对象 * * @param jsonData json数据 * @param beanType 对象中的object类型 * @return */ public static <T> T jsonToPojo(String jsonData, Class<T> beanType) throws JsonProcessingException { try { return MAPPER.readValue(jsonData, beanType); } catch (JsonProcessingException e) { log.error("json结果集转化为对象异常:{}", e.getLocalizedMessage()); throw e; } } /** * 将json数据转换成pojo对象list *

Title: jsonToList

*

Description:

* * @param jsonData * @param beanType * @return */
public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) { JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType); try { return MAPPER.readValue(jsonData, javaType); } catch (Exception e) { log.error("JSON Exception", e); } return null; } public static HashMap<String, Object> toHashMap(Object object) { HashMap<String, Object> data = new HashMap<>(); // 将json字符串转换成jsonObject JSONObject jsonObject = (JSONObject) object; Set<Map.Entry<String, Object>> entries = jsonObject.entrySet(); for (Map.Entry<String, Object> entry : entries) { if (entry == null) { continue; } data.put(entry.getKey(), entry.getValue()); } return data; } }

5 启动类

package com.yg.recursejson;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RecurseJsonApplication {

    public static void main(String[] args) {
        SpringApplication.run(RecurseJsonApplication.class, args);
    }

}

6 整个项目目录
包含JSONObject和JSONArray的json字符串进行递归取值,附源码(一)_第1张图片

代码测试

1 启动main函数,可以看到把json字符串的每个key和value都解析出来了

总结

如果是解析json字符串,应该还是算常用的递归




作为程序员第 93 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …

Lyric: 我们笑得很甜

你可能感兴趣的:(java开发常遇问题,fastJson)