[instanceof は文字列が JSON 型であるか JSONArray 型であるかを決定します]

instanceof は、文字列が JSON 型であるか JSONArray 型であるかを判断し、json を配列配列に変換します。

net.sf.json.util パッケージの下の JSONTokener を使用して決定します。

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());
    }
}

結果を出力します。
ここに画像の説明を挿入します

おすすめ

転載: blog.csdn.net/qq_45278500/article/details/126639154