You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用json-simple解析JSONArray遇异常,求将定义转为String[]的方法

解决方案:解析JSON数组并映射单词与定义

问题原因

你遇到的ClassCastException是因为直接将JSON值强转为JSONArray,如果JSON文件中存在某个单词对应的不是数组类型(比如拼写错误导致值变成字符串),就会触发这个异常。另外,json-simple本身需要手动处理类型转换,对新手不够友好。


方案1:修复json-simple代码

先做类型校验,再将JSONArray转换为String[],同时构建单词与定义的映射:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

private void loadJSONDictionary() {
    JSONObject jsonDictionary = null;
    JSONParser parser = new JSONParser();

    try (FileReader reader = new FileReader(this.fileName)) {
        jsonDictionary = (JSONObject) parser.parse(reader);
        // 存储单词与对应定义数组的映射
        Map<String, String[]> wordDefinitionMap = new HashMap<>();

        for (Object keyObj : jsonDictionary.keySet()) {
            String word = keyObj.toString();
            Object value = jsonDictionary.get(keyObj);

            // 先判断值是否为JSONArray类型,避免强转报错
            if (value instanceof JSONArray) {
                JSONArray definitionsArray = (JSONArray) value;
                String[] definitions = new String[definitionsArray.size()];
                
                // 将JSONArray元素逐个转为String,存入数组
                for (int i = 0; i < definitionsArray.size(); i++) {
                    definitions[i] = definitionsArray.get(i).toString();
                }
                
                wordDefinitionMap.put(word, definitions);
                
                // 测试输出
                System.out.println("单词: " + word);
                for (String def : definitions) {
                    System.out.println("定义: " + def);
                }
            } else {
                // 处理非数组的异常情况
                System.err.println("警告:单词 [" + word + "] 对应的不是数组类型");
            }
        }

        // 后续可通过wordDefinitionMap操作数据

    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
}

方案2:使用更易用的Gson库(推荐新手)

json-simple功能老旧,手动处理类型容易出错。Gson可以自动将JSON数组映射为String[],代码更简洁:

代码示例

import com.google.gson.Gson;
import java.io.FileReader;
import java.util.Map;

private void loadJSONWithGson() {
    Gson gson = new Gson();
    try (FileReader reader = new FileReader(this.fileName)) {
        // 直接解析为单词到String[]的映射,无需手动转换
        Map<String, String[]> wordDefinitionMap = gson.fromJson(reader, Map.class);

        // 遍历输出测试
        for (Map.Entry<String, String[]> entry : wordDefinitionMap.entrySet()) {
            System.out.println("单词: " + entry.getKey());
            for (String def : entry.getValue()) {
                System.out.println("定义: " + def);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

使用步骤

  1. 在IntelliJ中添加Gson库:打开File > Project Structure > Libraries,点击+号搜索Gson并添加。
  2. 替换原有的json-simple解析逻辑即可。

内容的提问来源于stack exchange,提问作者IntrACate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 11:05:57