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

如何反序列化含动态数字键的JSON?适配可变类名场景

处理带动态数字键的JSON反序列化方案

核心思路:JSON中user字段下的键是可变的数字字符串,因此需要用字典/映射类型来存储这些动态键值对,同时将每个键对应的用户数据封装为固定结构的实体类,以此适配任意动态数字键的场景。

以下是几种主流编程语言的实现方式:


Java(Jackson框架)

1. 定义用户实体类

封装用户的固定字段,忽略未知字段以兼容可选字段:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    private String id;
    private String created_timestamp;
    private String name;
    private String screen_name;
    private boolean protected;
    private boolean verified;
    private int followers_count;
    private int friends_count;
    private int statuses_count;
    private String profile_image_url;
    private String profile_image_url_https;
    // 可选字段
    private String location;
    private String description;

    // 生成无参构造、全参构造、getter和setter方法
}

2. 定义响应容器类

用Map<String, User>接收动态键的用户数据:

public class UserResponse {
    private Map<String, User> user;

    // getter和setter方法
}

3. 反序列化示例

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) throws Exception {
        String json = "{\"user\": {\"1330789870659362817\": {\"id\": \"xxxxxxxxxxxxxxxxxx\",\"created_timestamp\": \"1606120016282\",\"name\": \"yyyyyyyyyyyyy\",\"screen_name\": \"wwwwwwwww\",\"protected\": false,\"verified\": false,\"followers_count\": 9,\"friends_count\": 23,\"statuses_count\": 368,\"profile_image_url\": \"qqqqqqqqqqqqqqqq\",\"profile_image_url_https\": \"sssssssss\"},\"1467799120933003275\": {\"id\": \"wwwwwwwww\",\"created_timestamp\": \"1638785572496\",\"name\": \"cccccccccccc\",\"screen_name\": \"xxxxxxxxxxxx\",\"location\": \"xxxxxxxx\",\"description\": \"Cricket\",\"protected\": false,\"verified\": false,\"followers_count\": 1,\"friends_count\": 4,\"statuses_count\": 37,\"profile_image_url\": \"xxxxxx\",\"profile_image_url_https\": \"xxxxxxxxx\"}}}";

        ObjectMapper mapper = new ObjectMapper();
        UserResponse response = mapper.readValue(json, UserResponse.class);

        // 遍历所有动态键对应的用户
        for (Map.Entry<String, User> entry : response.getUser().entrySet()) {
            System.out.printf("动态用户ID:%s\n用户名:%s\n", entry.getKey(), entry.getValue().getName());
        }
    }
}

C#(Newtonsoft.Json框架)

1. 定义用户实体类

用JsonProperty标注字段映射关系:

using Newtonsoft.Json;

public class User
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("created_timestamp")]
    public string CreatedTimestamp { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("screen_name")]
    public string ScreenName { get; set; }

    [JsonProperty("protected")]
    public bool Protected { get; set; }

    [JsonProperty("verified")]
    public bool Verified { get; set; }

    [JsonProperty("followers_count")]
    public int FollowersCount { get; set; }

    [JsonProperty("friends_count")]
    public int FriendsCount { get; set; }

    [JsonProperty("statuses_count")]
    public int StatusesCount { get; set; }

    [JsonProperty("profile_image_url")]
    public string ProfileImageUrl { get; set; }

    [JsonProperty("profile_image_url_https")]
    public string ProfileImageUrlHttps { get; set; }

    // 可选字段,允许为null
    [JsonProperty("location")]
    public string Location { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }
}

2. 定义响应容器类

用Dictionary<string, User>存储动态键值对:

public class UserResponse
{
    [JsonProperty("user")]
    public Dictionary<string, User> UserMap { get; set; }
}

3. 反序列化示例

using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        string json = @"{
          ""user"": {
            ""1330789870659362817"": {
              ""id"": ""xxxxxxxxxxxxxxxxxx"",
              ""created_timestamp"": ""1606120016282"",
              ""name"": ""yyyyyyyyyyyyy"",
              ""screen_name"": ""wwwwwwwww"",
              ""protected"": false,
              ""verified"": false,
              ""followers_count"": 9,
              ""friends_count"": 23,
              ""statuses_count"": 368,
              ""profile_image_url"": ""qqqqqqqqqqqqqqqq"",
              ""profile_image_url_https"": ""sssssssss""
            },
            ""1467799120933003275"": {
              ""id"": ""wwwwwwwww"",
              ""created_timestamp"": ""1638785572496"",
              ""name"": ""cccccccccccc"",
              ""screen_name"": ""xxxxxxxxxxxx"",
              ""location"": ""xxxxxxxx"",
              ""description"": ""Cricket"",
              ""protected"": false,
              ""verified"": false,
              ""followers_count"": 1,
              ""friends_count"": 4,
              ""statuses_count"": 37,
              ""profile_image_url"": ""xxxxxx"",
              ""profile_image_url_https"": ""xxxxxxxxx""
            }
          }
        }";

        UserResponse response = JsonConvert.DeserializeObject<UserResponse>(json);

        foreach (var kvp in response.UserMap)
        {
            System.Console.WriteLine($"动态用户ID:{kvp.Key}");
            System.Console.WriteLine($"用户名:{kvp.Value.Name}");
        }
    }
}

Python(dataclasses + json模块)

1. 定义用户数据类

用dataclasses简化实体类定义,可选字段设为Optional类型:

from dataclasses import dataclass
import json
from typing import Dict, Optional

@dataclass
class User:
    id: str
    created_timestamp: str
    name: str
    screen_name: str
    protected: bool
    verified: bool
    followers_count: int
    friends_count: int
    statuses_count: int
    profile_image_url: str
    profile_image_url_https: str
    location: Optional[str] = None
    description: Optional[str] = None

@dataclass
class UserResponse:
    user: Dict[str, User]

2. 反序列化示例

自定义解码器将JSON数据映射到数据类:

def decode_user_response(json_str: str) -> UserResponse:
    data = json.loads(json_str)
    user_map = {user_id: User(**user_data) for user_id, user_data in data["user"].items()}
    return UserResponse(user=user_map)

# 测试代码
json_data = '''
{
  "user": {
    "1330789870659362817": {
      "id": "xxxxxxxxxxxxxxxxxx",
      "created_timestamp": "1606120016282",
      "name": "yyyyyyyyyyyyy",
      "screen_name": "wwwwwwwww",
      "protected": false,
      "verified": false,
      "followers_count": 9,
      "friends_count": 23,
      "statuses_count": 368,
      "profile_image_url": "qqqqqqqqqqqqqqqq",
      "profile_image_url_https": "sssssssss"
    },
    "1467799120933003275": {
      "id": "wwwwwwwww",
      "created_timestamp": "1638785572496",
      "name": "cccccccccccc",
      "screen_name": "xxxxxxxxxxxx",
      "location": "xxxxxxxx",
      "description": "Cricket",
      "protected": false,
      "verified": false,
      "followers_count": 1,
      "friends_count": 4,
      "statuses_count": 37,
      "profile_image_url": "xxxxxx",
      "profile_image_url_https": "xxxxxxxxx"
    }
  }
}
'''

response = decode_user_response(json_data)
for user_id, user in response.user.items():
    print(f"动态用户ID:{user_id}")
    print(f"用户名:{user.name}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:50:27