Convert character data in json format to map format

Record it, write an interesting operation encountered in the project;

For example, after querying data in the back-end java, the format of the original data obtained from the database is as follows: (it may be stored in the form of a string in json format when stored in the database or in es )

 But the data format required by the front end is as follows:

颜色:蓝色,黑色,金色,粉色

版本:6GB+128GB,4GB+64GB

There are quite a lot of businesses in this scenario: for example, the display of commodity specifications in the most common shopping websites: for example

Directly use the queried raw data and return it to the front end. It may not be easy for the front end to display these specification data, so it needs to be converted into a map and then returned to the front end.

The code to convert the specification format is as follows:

The key points involved in it:

1. The traversal method of map -- master at least one or two

2. Conversion between string data in json format and various objects -- using the tool library

3. When using keySet to traverse the map, be careful to obtain the value in advance. This operation can shape the data typology of the value in advance. Also handles null values.

    /**
     * 规格转化方法  开始我们给前端的数据格式  用手机举例
     * specList 中的数据如下格式:
     * [
     * "{'颜色': '蓝色', '版本': '6GB+128GB'}",
     * "{'颜色': '黑色', '版本': '6GB+128GB'}",
     * "{'颜色': '黑色'}",
     * "{'颜色': '蓝色'}",
     * ]
     * ======》 前端实际需要的数据格式:
     * 颜色:【蓝色,黑色,金色,粉色】
     * 版本:【6GB+128GB,4GB+64GB】
     *
     * 返回的参数怎么确定?方法应该接收什么类型的参数?
     * 返回的数据格式上面已经写了,肯定是map的数据,但是map的泛型就有讲究了,我们要保证value里面的数据
     * 没有重复,所以这里不使用list了,使用的是set;
     * 接收的参数:我们打算对规格的参数列表进行转换,所以方法的参数肯定是规格参数列表
     */
    public Map<String, Set<String>> formatSpec(List<String> specList){
        Map<String, Set<String>> resultMap = new HashMap<>();
        //遍历list
        for (String specStr : specList) {
            //specStr json格式的string串 ====> "{'颜色': '蓝色', '版本': '6GB+128GB'}"
            Map<String, String> specMap = JSON.parseObject(specStr, Map.class); //颜色:蓝色 版本:6GB+128GB
            //遍历map  map的遍历必须要会那么至少一种
            for (String key : specMap.keySet()) {
//key 颜色    value 蓝色  resultMap.get(key)这个操作着实没有看懂.....
// --> 通过查询资料发现这个是keySet遍历的要求:必须先去取一次key的值
//但是为什么不用  specMap.get(key) 来取第一次值嘞?当然可以,但是那个时候resultMap的value值就不好赋值了
//specMap.get(key)取到的value的值的类型是string,而我们需要的是Set<String>,第一次的getKey(得到的是value)可以帮我们完成keySet对value的数据类型转换
                Set<String> valueSet = resultMap.get(key);  //valueSet:【蓝色,黑色,金色,粉色】
                if(valueSet == null){
                    valueSet = new HashSet<>();
                }
                valueSet.add(specMap.get(key));

                resultMap.put(key,valueSet);
            }
        }

        return resultMap;
    }

Finally, test it in the project: the display result is 

Guess you like

Origin blog.csdn.net/weixin_53142722/article/details/126517148