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

Java使用json-simple库如何根据JSON值获取对应键

使用json-simple根据值查找对应键的实现方案

首先引入json-simple依赖,以Maven为例:

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

json-simple的JSONObject本质继承自HashMap,直接遍历键值对匹配目标值即可,完整实现代码如下:

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.util.Map;

public class FindKeyByValueDemo {
    public static void main(String[] args) {
        // 输入的JSON字符串
        String jsonContent = "{\"a\": \"X1abs\",\"b\": \"d4vT\"}";
        // 要匹配的目标值
        String targetValue = "X1abs";
        // 存储匹配到的键
        String matchedKey = null;

        try {
            // 解析JSON字符串为JSONObject对象
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonContent);

            // 遍历所有键值对
            for (Map.Entry entry : jsonObject.entrySet()) {
                if (targetValue.equals(entry.getValue())) {
                    matchedKey = (String) entry.getKey();
                    // 若存在多个键对应同一个值的场景,去掉break用List收集所有匹配键即可
                    break;
                }
            }

            // 输出结果
            if (matchedKey != null) {
                System.out.println("匹配到的键:" + matchedKey);
            } else {
                System.out.println("未找到对应值的键");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

运行代码会输出匹配到的键:a,符合需求。

注意事项

  • 比较值的时候用目标值调用equals方法,避免目标值为null时触发空指针异常
  • 如果业务场景存在多个键对应同一个值的情况,删除break语句,用List集合存储所有匹配的键即可
  • 若使用json-simple 2.x版本,仅需修改对应import的包路径,遍历逻辑完全兼容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:42:03