多个第三方JSON根据配置映射为规定的JSON

第一版

再对接多个第三方的时候,返回的json及json格式、json结构可能不一致

有的可能是这样的:
 

{
	"payload": {
		"data": [{
			"name1":"nA",
			"value1":"bB",
			"dtype": {
				"code": "78978977898",
				"name": "4645645656445"
			},
		}],
		"status": "SUCCESS"
	},
	"header": {
		"pv": "1.0",
		"oid": "123"
	}
}

也有的可能是这样的:
 

{
    "1": {
        "type": "abc",
        "name": "abca",
        "value": {
            "dd": "dd",
            "cc": "cc",
            "ee": "ee",
            "ff": {
                "fa": "faa",
                "fb": fbb
            }
        },
    }
}

还有可能是这样的:
 

{
    "requestId": "798456130",
    "code": 200,
    "message": "成功",
    "data": [
        {
            "aa": "aa",
            "qw": "qw",
            "qwe": "qwe",
            "er": "er",
            "wt": "wt1",
            "wt2": "wt2"
        }
    ]
}

可能各不相同,废话不多说了

第一步:定义规则:
第一个例子规则为:

{
	"type": "Object",
	"property": [{
		"name": "payload.data",
		"type": "List",
		"mapName": "data",
		"mapValue": "value",
		"property": [{
			"name": "name1",
			"type": "String",
			"mapValue": "value",
			"mapName": "name"
		}, {
			"name": "value1",
			"type": "String",
			"mapValue": "value",
			"mapName": "value"
		}, {
			"name": "dtype.code",
			"type": "String",
			"mapValue": "value",
			"mapName": "type"
		}, {
			"name": "dtype.name",
			"type": "String",
			"mapValue": "value",
			"mapName": "dtypename"
		}]
	}]
}

第二步骤:定义规则类

@NoArgsConstructor
@Data
public class InterMap {
    @JSONField(name = "type")
    private String type;
    @JSONField(name = "property")
    private List<PropertyBean> property;

    @NoArgsConstructor
    @Data
    public static class PropertyBean {
        @JSONField(name = "name")
        private String name;
        @JSONField(name = "type")
        private String type;
        @JSONField(name = "mapName")
        private String mapName;
        @JSONField(name = "mapValue")
        private String mapValue;
        @JSONField(name = "property")
        private List<PropertyBean> property;
    }
}

第三步:写方法 (此方法可以继续优化,如可写成递归函数、用反射等等,这里暂不优化,后续再加进来)

public static String parseMapDbList(String dbJson, String originJson){
        Map<String, Object> resultMap = Maps.newHashMap();
        try {
            InterMap interMap = JSONObject.parseObject(dbJson, InterMap.class);
            cn.hutool.json.JSONObject originJsonObject = JSONUtil.parseObj(originJson);
            List<InterMap.PropertyBean> propertyBeanList = interMap.getProperty();
            propertyBeanList.stream().forEach(propertyBean -> {
                String name = propertyBean.getName();
                String type = propertyBean.getType();
                List data = Lists.newArrayList();
                String mapName = propertyBean.getMapName();
                List<InterMap.PropertyBean> sunPropertyList = propertyBean.getProperty();
                if (type.equals("List")){
                    List originList = originJsonObject.getByPath(name, List.class);
                    originList.stream().forEach(o -> {
                        Map<String, Object> map = Maps.newHashMap();
                        sunPropertyList.stream().forEach(propertyBean1 -> {
                            String name1 = propertyBean1.getName();
                            String mapValue = propertyBean1.getMapValue();
                            String type1 = propertyBean1.getType();
                            Object byPath = null;
                            if (mapValue.equalsIgnoreCase("value")){
                                byPath = JSONUtil.getByPath(JSONUtil.parse(o), name1);
                            }
                            if (type1.equals("String")){
                                map.put(propertyBean1.getMapName(), byPath);
                            }
                        });
                        data.add(map);
                    });
                } else if (type.equals("Map")){
                    Map originMap = originJsonObject;
                    originMap.keySet().stream().forEach(o -> {
                        Map<String, Object> map = Maps.newHashMap();
                        sunPropertyList.stream().forEach(propertyBean1 -> {
                            String name1 = propertyBean1.getName();
                            String mapValue = propertyBean1.getMapValue();
                            String type1 = propertyBean1.getType();
                            Object byPath = null;
                            if (mapValue.equalsIgnoreCase("value")){
                                byPath = JSONUtil.getByPath(JSONUtil.parse(originMap.get(o)), name1);
                            }
                            if (mapValue.equalsIgnoreCase("p-key")){
                                byPath = o;
                            }
                            if (type1.equals("String")){
                                map.put(propertyBean1.getMapName(), byPath);
                            }
                        });
                        data.add(map);
                    });
                }
                resultMap.put(mapName, data);
            });
            return JSONUtil.toJsonStr(resultMap);
        } catch (Exception e){
            log.error("映射第三方数据 | originJson : {}, dbJson : {}", originJson, dbJson);
            log.error("映射第三方数据失败:{}", e);
        }
        return null;
    }

用到的第三方包为:hutool

优化第一版

1.优化规则类

@NoArgsConstructor
@Data
public class DataMapRule {

    @JSONField(name = "type")
    private String type;

    @JSONField(name = "success")
    private String success;

    @JSONField(name = "property")
    private List<PropertyBean> property;

    @NoArgsConstructor
    @Data
    public static class PropertyBean {

        @JSONField(name = "name")
        private String name;

        @JSONField(name = "type")
        private String type;

        @JSONField(name = "mapType")
        private String mapType;

        @JSONField(name = "mapName")
        private String mapName;

        @JSONField(name = "mapValue")
        private String mapValue;

        @JSONField(name = "valueProp")
        private Map<String, Object> valueProp;

        @JSONField(name = "property")
        private List<PropertyBean> property;
    }
}

2.优化json类

public static String RESULT_CODE = "code";

public static String parseDbMap(String dbJson, String originJson){
        try {
            DataMapRule dataMapRule = JSONObject.parseObject(dbJson, DataMapRule.class);
            Object parse = JSONObject.parse(originJson);
            JSON originJsonObject = JSONUtil.parse(parse);
            String success = dataMapRule.getSuccess();
            List<DataMapRule.PropertyBean> propertyBeanList = dataMapRule.getProperty();
            Map<String, Object> resultMap = recursion(propertyBeanList, originJsonObject);
            if (MapUtil.isNotEmpty(resultMap) && ObjectUtil.isNotEmpty(resultMap.get(SystemConstants.RESULT_CODE)) && StrUtil.isNotBlank(success)){
                if (Convert.toStr(resultMap.get(SystemConstants.RESULT_CODE)).equals(success)){
                    resultMap.put("code",0);
                } else {
                    resultMap.put("code",-1);
                }
            }
            return JSONUtil.toJsonStr(resultMap);
        }catch (Exception e){
            log.warn("映射第三方数据2 | originJson : {}, dbJson : {}", originJson, dbJson);
            log.warn("映射第三方数据失败:{}", e);
        }
        return dbJson;
    }


private static Map<String, Object> recursion(List<DataMapRule.PropertyBean> propertyBeanList, JSON originJsonObject){
        Map<String, Object> resultMap = Maps.newHashMap();
        if (CollUtil.isNotEmpty(propertyBeanList)){
            propertyBeanList.stream().forEach(propertyBean -> {
                String path = propertyBean.getName();
                String type = propertyBean.getType();
                String mapType = propertyBean.getMapType();
                String mapName = propertyBean.getMapName();
                String mapValue = propertyBean.getMapValue();
                Map<String,Object> valueProp = propertyBean.getValueProp();
                List<DataMapRule.PropertyBean> sunPropertyList = propertyBean.getProperty();
                if (BASE_LIST.equals(type)){
                    toList(resultMap, originJsonObject, path, mapName,mapType, sunPropertyList);
                } else if (BASE_MAP.equals(type)){
                    toMap(resultMap, originJsonObject, path, mapName,mapType, sunPropertyList);
                } else if(BASE_OBJECT.equals(type)){
                    toObject(resultMap, originJsonObject, path, mapName,mapType, sunPropertyList);
                }  else if(BASE_KEY_VAL.equals(type)){
                    toListMap(resultMap, originJsonObject, mapValue, mapName);
                } else {
                    toBasic(resultMap, originJsonObject, path, mapName,mapType, valueProp);
                }
            });
            return resultMap;
        }
        return resultMap;
    }
 /** 递归
     * 适合:dbjson= {}
     * 源json={
     *     list:[
     *         {key:val}
     *     ]
     * }
     * @param resultMap
     * @param originJsonObject
     * @param path
     * @param mapName
     * @param mapType
     * @param sunPropertyList
     */
    private static void toList(Map<String, Object> resultMap,JSON originJsonObject,
                        String path, String mapName,String mapType, List<DataMapRule.PropertyBean> sunPropertyList){
        if (StrUtil.isBlank(mapType)){
            List data = Lists.newArrayList();
            List originList = originJsonObject.getByPath(path, List.class);
            originList.stream().forEach(o -> {
                if (o instanceof String || ObjectUtil.isBasicType(o)){
                    data.add(o);
                    return;
                }
                Map<String, Object> recursion = recursion(sunPropertyList, JSONUtil.parse(o));
                data.add(recursion);
            });
            resultMap.put(mapName, data);
            return;
        }
        listToMap(resultMap, originJsonObject, path, mapName, mapType, sunPropertyList);
    }
    public static final String MAP = "Map";
    private static void listToMap(Map<String, Object> resultMap,JSON originJsonObject,
                        String path, String mapName,String mapType, List<DataMapRule.PropertyBean> sunPropertyList){
        if (MAP.equals(mapType)){
            Map<String, Object> dataMap = Maps.newHashMap();
            List originList = originJsonObject.getByPath(path, List.class);
            originList.stream().forEach(o -> {
                Map<String, Object> recursion = recursion(sunPropertyList, JSONUtil.parse(o));
                dataMap.putAll(recursion);
            });
            resultMap.put(mapName, dataMap);
            return;
        }
    }

    private static void toMap(Map<String, Object> resultMap,JSON originJsonObject, String path, String mapName,String mapType, List<DataMapRule.PropertyBean> sunPropertyList){
        List data = Lists.newArrayList();
        Map originMap = originJsonObject.toBean(Map.class);
        if (CollUtil.isNotEmpty(sunPropertyList)){
            boolean present = sunPropertyList.stream().filter(pb -> BASE_PARENT_KEY.equalsIgnoreCase(pb.getMapValue())).findAny().isPresent();
            originMap.keySet().stream().forEach(key -> {
                Map<String, Object> recursion = recursion(sunPropertyList, JSONUtil.parse(originMap.get(key)));
                if (present) {
                    sunPropertyList.stream()
                            .filter(pb -> BASE_PARENT_KEY.equalsIgnoreCase(pb.getMapValue()))
                            .forEach(propertyBean1 -> {
                                String mapValue1 = propertyBean1.getMapValue();
                                if (BASE_PARENT_KEY.equalsIgnoreCase(mapValue1)){
                                    recursion.put(propertyBean1.getMapName(), key);
                                }
                            });
                }
                data.add(recursion);
            });
            resultMap.put(mapName, data);
        } else {
            Object o = originMap.get(path);
            if (StrUtil.isBlank(mapName)){
                Map<String, Object> map1 = (Map<String, Object>) o;
                resultMap.putAll(map1);
                return;
            }
            resultMap.put(mapName, o);
        }
    }

    private static void toBasic(Map<String, Object> resultMap,JSON originJsonObject,
                                String path, String mapName,String mapType,
                                Map<String,Object> valueProp){
        Object byPath = originJsonObject.getByPath(path);
        if (CollUtil.isNotEmpty(valueProp)) {
            byPath = valueProp.get(String.valueOf(byPath));
        }
        resultMap.put(mapName, byPath);
    }

    /** 不是递归-终结
     *
     * example : {"cmd":"key","data":"val"} => {"key":"val"}
     *
     * key 和 val 均为源数据某个属性的值
     * @param resultMap
     * @param originJsonObject
     * @param mapValue
     * @param mapName
     */
    private static void toListMap(Map<String, Object> resultMap,JSON originJsonObject,
                                  String mapValue, String mapName){
        Object key = originJsonObject.getByPath(mapName);
        Object value = originJsonObject.getByPath(mapValue);
        String strKey = String.valueOf(key);
        if (StrUtil.isNotBlank(strKey)){
            resultMap.put(String.valueOf(key), value);
        }
    }
    private static void toObject(Map<String, Object> resultMap,JSON originJsonObject,
                                 String path, String mapName, String mapType, List<DataMapRule.PropertyBean> sunPropertyList){
        Object byPath = originJsonObject.getByPath(path);
        if (CollUtil.isNotEmpty(sunPropertyList)){
            Map<String, Object> recursion = recursion(sunPropertyList, JSONUtil.parse(byPath));
            resultMap.put(mapName, recursion);
            return;
        }
        resultMap.put(mapName, byPath);
    }
dbjson案例1:

{"type":"Object","property":[{"name":"action","type":"String","mapName":"action","mapValue":"value"},{"name":"deviceId","type":"String","mapName":"deviceId","mapValue":"value"},{"name":"status","type":"Map","mapName":"property","mapValue":"value"}]}

dbjson案例2:

{"type":"Object","success":"200","property":[{"name":"code","type":"String","mapName":"code","mapValue":"value"},{"name":"message","type":"String","mapName":"msg","mapValue":"value"}]}

dbjson案例3:适用:如:张三的学号为123,李四的学号为456。originJson:{"123":{"name":"张三","age":"18"},"456":{"name":"李四","age":"20"}}

{"type":"Object","property":[{"name":"key","type":"Map","mapName":"data","property":[{"name":"key","type":"String","mapValue":"p-key","mapName":"deviceId"},{"name":"type","type":"String","mapValue":"value","mapName":"productKey"},{"name":"productname","type":"String","mapValue":"value","mapName":"deviceName"},{"name":"type","type":"String","mapValue":"value","mapName":"productType"}]}]}

后面可用java的设计模式进行优化,下次在加进来

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 在Java中,可以使用Apache POI库来将JSON转换为Excel文件。 Apache POI是一个流行的Java类库,通常用于创建、读取和修改Microsoft Office文件,包括Excel文件。 要将JSON转换为Excel,首先需要解析JSON数据并将其转换为Java对象。可以使用第三方库,如Jackson或Gson,来帮助解析JSON。这些库提供了将JSON字符串转换为Java对象的方法。 一旦将JSON数据转换为Java对象,就可以使用Apache POI来创建Excel文件。POI提供了一系列类和方法,可以创建Excel工作簿、工作表以及单元格,并设置单元格的值和格式。 以下是一个简单的示例代码,演示如何将JSON转换为Excel使用Apache POI: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.util.List; public class JsonToExcelConverter { public static void convertToExcel(List<MyObject> objects, String outputFilePath) { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); int rowNum = 0; for (MyObject obj : objects) { Row row = sheet.createRow(rowNum++); Cell cell1 = row.createCell(0); cell1.setCellValue(obj.getField1()); Cell cell2 = row.createCell(1); cell2.setCellValue(obj.getField2()); // 添加更多的单元格和字段 } try (FileOutputStream outputStream = new FileOutputStream(outputFilePath)) { workbook.write(outputStream); workbook.close(); System.out.println("Excel文件成功创建!"); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // 解析JSON并得到Java对象列表 List<MyObject> objects = parseJson("data.json"); // 将Java对象列表转换为Excel文件 convertToExcel(objects, "output.xlsx"); } } class MyObject { private String field1; private int field2; // 省略构造函数和getter/setter方法 } ``` 以上示例代码使用了XSSF工作簿和Sheet类来创建Excel文件,并使用Row和Cell类来设置单元格的值。通过调用Workbook的write()方法,可以将Excel文件写入磁盘。 请注意,此示例代码假设已经解析了名为"data.json"的JSON文件,并将其转换为MyObject对象的列表。您需要根据自己的数据结构和要求进行修改。 ### 回答2: 在Java中,有许多类库可以帮助我们将JSON数据转换为Excel文件。以下是其中几个比较常用的类库: 1. Apache POI:Apache POI是一款非常流行的Java类库,可以用来创建和处理Microsoft Office格式的文件,包括Excel。我们可以使用POI的HSSF和XSSF组件来将JSON数据转换为Excel文件。首先,我们需要解析JSON数据并将其转换为Java对象,然后使用POI提供的API将数据写入Excel文件。 2. Gson:Gson是Google提供的一款功能强大的JSON解析库。虽然Gson本身不提供直接将JSON转换为Excel的功能,但我们可以使用它将JSON数据解析为Java对象,然后使用Apache POI等其他类库将Java对象转换为Excel文件。 3. Jackson:Jackson是另一款流行的JSON解析库,也可以用来处理将JSON转换为Excel。类似于Gson,我们可以使用Jackson将JSON数据解析为Java对象,然后使用其他类库将Java对象转换为Excel文件。 总结来说,我们可以使用Apache POI、Gson或Jackson等类库将JSON数据转换为Excel文件。具体的实现细节可以根据具体的需求和项目来选择合适的类库和方法。 ### 回答3: JSON转Excel是一种将JSON数据转换为Excel文件格式的操作。在Java中,有多个类库可以实现这个功能。 其中最常用的类库是Apache POI(Poor Obfuscation Implementation)和EasyExcel。 Apache POI是一个用于操作各种Office文件格式的Java API。它提供了一套丰富的类和方法,可以创建、修改和读取Excel文件。要将JSON数据转换为Excel,可以使用POI的相关类库,如Workbook、Sheet和Row等,将JSON中的数据逐行逐列地写入Excel文件中。 另外,EasyExcel是一款基于POI封装的简单易用的Java类库,它提供了更加简洁和便捷的API,能够快速地实现JSON到Excel的转换。EasyExcel提供了注解形式的编程方式,可以方便地将JSON中的属性与Excel中的列进行映射,并且支持多种导入导出格式,如XLS、XLSX、CSV等。 使用以上两种类库进行JSON转Excel的步骤大致相同,包括读取JSON数据、创建Excel文件、处理数据映射和写入Excel文件等。 需要注意的是,由于Excel文件的特殊格式,对于大量数据的处理可能会比较耗时和占用内存。因此,在处理大规模的JSON数据转换时,应该注意性能和资源消耗的问题。另外,在选择类库时,也需要考虑项目的需求和实际情况,选择适合的类库来实现JSON转Excel功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值