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

如何使用Swift 4 Coding Keys处理JSON响应中的动态键

处理含动态键的JSON响应

嗨,这种带动态键的JSON响应在API交互里挺常见的,尤其是像社交平台这类返回用户相关数据的接口。下面我分几种主流编程语言给你讲讲具体的处理思路:

JavaScript/TypeScript

在JS/TS里,我们可以借助Object.keys()、Object.values()或者Object.entries()来轻松处理动态键:

方式1:遍历动态键并处理对应数据

const response = { 
  "code": 200, 
  "message": "Top Likers info.", 
  "error": null, 
  "data": { 
    "manishamohapatra11": { 
      "id": "5591322611", 
      "username": "manishamohapatra11", 
      "full_name": ":-)Sunshine :-)", 
      "profile_pic_url": "https://scontent-atl3-1.cdninstagram.com/vp/d2ba431ac70ec067d5d6def73a721250/5B553C8E/t51.2885-19/s150x150/27877706_168319037141873_8387886458379173888_n.j..." 
    } 
  } 
};

// 用Object.entries直接拿到键值对,直观又方便
Object.entries(response.data).forEach(([username, userInfo]) => {
  console.log(`用户名:${username}`);
  console.log(`用户全名:${userInfo.full_name}`);
  console.log(`头像链接:${userInfo.profile_pic_url}`);
  // 这里可以根据业务需求做渲染、存储等操作
});

方式2:只提取用户数据(不关心键名)

如果不需要动态键本身,直接用Object.values()提取所有用户信息数组:

const users = Object.values(response.data);
users.forEach(user => {
  console.log(`用户ID:${user.id}`);
});

Python

Python处理这种动态键字典非常顺手,直接遍历字典的items()方法就行:

import json

# 假设已经拿到响应的JSON字符串,先解析为字典
response_json = '''{ 
  "code": 200, 
  "message": "Top Likers info.", 
  "error": null, 
  "data": { 
    "manishamohapatra11": { 
      "id": "5591322611", 
      "username": "manishamohapatra11", 
      "full_name": ":-)Sunshine :-)", 
      "profile_pic_url": "https://scontent-atl3-1.cdninstagram.com/vp/d2ba431ac70ec067d5d6def73a721250/5B553C8E/t51.2885-19/s150x150/27877706_168319037141873_8387886458379173888_n.j..." 
    } 
  } 
}'''
response = json.loads(response_json)

# 遍历data中的动态键值对
for username, user_info in response['data'].items():
    print(f"用户名:{username}")
    print(f"用户ID:{user_info['id']}")
    print(f"用户全名:{user_info['full_name']}")

# 若只需要用户信息列表,直接取values即可
users = list(response['data'].values())
for user in users:
    print(f"头像链接:{user['profile_pic_url']}")

Java

在Java里,我们可以用Map来接收动态键部分,再通过遍历entrySet()处理数据,这里以常用的Jackson库为例:

方式1:用JsonNode灵活处理

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

public class DynamicKeyHandler {
    public static void main(String[] args) throws IOException {
        String responseJson = "{ \"code\": 200, \"message\": \"Top Likers info.\", \"error\": null, \"data\": { \"manishamohapatra11\": { \"id\": \"5591322611\", \"username\": \"manishamohapatra11\", \"full_name\": \":-)Sunshine :-)\", \"profile_pic_url\": \"https://scontent-atl3-1.cdninstagram.com/vp/d2ba431ac70ec067d5d6def73a721250/5B553C8E/t51.2885-19/s150x150/27877706_168319037141873_8387886458379173888_n.j...\" } } }";
        
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(responseJson);
        JsonNode dataNode = rootNode.get("data");
        
        // 遍历所有动态键值对
        Iterator<Map.Entry<String, JsonNode>> fields = dataNode.fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> entry = fields.next();
            String username = entry.getKey();
            JsonNode userNode = entry.getValue();
            
            String userId = userNode.get("id").asText();
            String fullName = userNode.get("full_name").asText();
            
            System.out.println("用户名:" + username);
            System.out.println("用户ID:" + userId);
            System.out.println("用户全名:" + fullName);
        }
    }
}

方式2:结合实体类用Map接收

如果有对应的User实体类,可以直接把data解析为Map<String, User>:

// 先定义User实体类
public class User {
    private String id;
    private String username;
    private String full_name;
    private String profile_pic_url;
    
    // 省略getter、setter和构造方法
}

然后解析并处理:

Map<String, User> userMap = objectMapper.readValue(
    rootNode.get("data").traverse(),
    new TypeReference<Map<String, User>>() {}
);

for (Map.Entry<String, User> entry : userMap.entrySet()) {
    String username = entry.getKey();
    User user = entry.getValue();
    // 按需处理用户数据
}

总的来说,核心思路就是不要依赖固定键名,而是通过遍历键值对的方式处理动态内容,不同语言的API略有差异,但逻辑是一致的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:51:39