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

如何在Java中根据条件从JSON数组响应中查找字符串

从F1车手JSON响应中查找字符串的方法

嘿,我来帮你搞定从这个2016年F1车手的JSON响应里查找指定字符串的事儿!下面给你举几个实用的例子,你可以根据自己的需求调整条件:

先准备好完整的JSON数据

首先咱们把你提供的截断JSON补全(原数据里familyNam...应该是familyName),方便后续操作:

{ 
  "MRData": { 
    "xmlns": "http://ergast.com/mrd/1.4", 
    "series": "f1", 
    "url": "http://ergast.com/api/f1/2016/drivers.json", 
    "limit": "30", 
    "offset": "0", 
    "total": "24", 
    "DriverTable": { 
      "season": "2016", 
      "Drivers": [ 
        { 
          "driverId": "alonso", 
          "permanentNumber": "14", 
          "code": "ALO", 
          "url": "http://en.wikipedia.org/wiki/Fernando_Alonso", 
          "givenName": "Fernando", 
          "familyName": "Alonso"
        }
        // 这里可以包含其他23位车手的数据
      ] 
    } 
  }
}

具体查找示例(以JavaScript为例)

1. 精准匹配单个车手(比如找driverId为"alonso"的)

用find方法可以快速定位到第一个符合条件的结果:

// 假设jsonData是上面的完整JSON对象
const targetDriverId = "alonso";
const foundDriver = jsonData.MRData.DriverTable.Drivers.find(driver => driver.driverId === targetDriverId);

if (foundDriver) {
  console.log(`找到目标车手:${foundDriver.givenName} ${foundDriver.familyName}`);
} else {
  console.log("没有找到符合条件的车手");
}

2. 模糊匹配所有符合条件的车手(比如找名字里包含"Fern"的)

如果想要找出所有名字里包含特定字符串的车手,用filter方法就能获取所有匹配结果:

const searchKeyword = "Fern";
const matchingDrivers = jsonData.MRData.DriverTable.Drivers.filter(driver => 
  driver.givenName.includes(searchKeyword) || driver.familyName.includes(searchKeyword)
);

console.log(`共找到${matchingDrivers.length}个符合条件的车手:`, matchingDrivers);

3. 自定义其他查找条件

你完全可以根据自己的需求修改判断逻辑,比如找永久号码是"14"的,或者车手代码是"ALO"的,只需要把find/filter里的判断条件换成对应的字段就行:

// 找永久号码为"14"的车手
const targetNumber = "14";
const driverWithNumber = jsonData.MRData.DriverTable.Drivers.find(driver => driver.permanentNumber === targetNumber);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:57:47