[instanceof determines whether a string is of JSON type or JSONArray type]

instanceof determines whether the string is of JSON type or JSONArray type, and converts json into an array array

Use JSONTokener under the net.sf.json.util package to determine

package com.sense.iam.sso.action;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONTokener;

/**
 * @author z
 * @create 2022-08-31 12:16
 */
public class Test {
    
    
    public static void main(String[] args) {
    
    
        String result = "{\"roleList\":[{\"roleCode\":\"HYJK-CRM-0001\",\"roleName\":\"系统管理员\"},{\"roleCode\":\"HYJK-CRM-0002\",\"roleName\":\"角色管理员\"}],\"jobList\":{\"jobCode\":\"ZWWL0040\",\"jobPosition\":\"应用系统项目经理\"}}";
        System.out.println(result);


        com.alibaba.fastjson.JSONObject resultJSON = com.alibaba.fastjson.JSONObject.parseObject(result);
        Object jobValue = new JSONTokener(resultJSON.get("jobList").toString()).nextValue();
        Object roleValue = new JSONTokener(resultJSON.get("roleList").toString()).nextValue();
        if(resultJSON.containsKey("jobList")){
    
    
            if(jobValue instanceof JSONObject){
    
    
                com.alibaba.fastjson.JSONArray jobList = new com.alibaba.fastjson.JSONArray();
                jobList.add(resultJSON.get("jobList"));
                resultJSON.put("jobList",jobList);
            }
        }
        if(resultJSON.containsKey("roleList")){
    
    
            if(roleValue instanceof JSONObject){
    
    
                com.alibaba.fastjson.JSONArray roleList = new com.alibaba.fastjson.JSONArray();
                roleList.add(resultJSON.get("roleList"));
                resultJSON.put("roleList",roleList);
            }
        }
        System.out.println(resultJSON.toString());
    }
}

Print the result:
Insert image description here

Guess you like

Origin blog.csdn.net/qq_45278500/article/details/126639154