各类标点符号分隔的字符串转JSON对象

各类标点符号分隔的字符串转JSON对象

import cn.hutool.json.JSONObject;

/**
 * @Description :
 * @Author : sherlockerSun
 * @Date : 2021/10/11 17:14
 */
public class test {
    public static void main(String[] args) {
        String str="name:张三,age:10,sex:男";
        JSONObject jsonObject=new JSONObject(String.format("{%s}", str.replaceAll("([^,]+)\\s*?,\\s*?([^,]+)(,|$),([^,]+)(:|$)", "$1:$2,")));

        System.out.println(jsonObject.toString());
    }
}

结果:

{"sex":"男","name":"张三","age":10}

若存在空值

import cn.hutool.json.JSONObject;

/**
 * @Description :
 * @Author : sherlockerSun
 * @Date : 2021/10/11 17:14
 */
public class test {
    public static void main(String[] args) {
        String str="name:张三,age:,sex:男,num:";
        str=str.replaceAll(":,",":'',");
        //若结尾为空值
        if (str.substring(str.length()-1, str.length()).equals(":")){
            str=str+"''";
        }
        JSONObject jsonObject = new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|$),([^,]+)(:|$)", "$1:$2,")));
        System.out.println(jsonObject.toString());
    }
}

结果:

{"sex":"男","num":"","name":"张三","age":""}
posted @ 2021-10-12 09:44  SherlockerSun  阅读(19)  评论(0)    收藏  举报