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

如何使用Jackson2解析含随机对象键的JSON数据?

用Jackson2解析带动态随机键的JSON(Java实现)

嘿,这种带动态随机键的JSON解析在Jackson里其实很容易搞定,我给你两种常用的实现方式,按需选择就行:

方案一:直接用Map接收动态键

这是最直观的方式,把attachment字段定义为Map<String, AttachmentItem>,其中AttachmentItem是对应每个随机键下的附件实体类。

第一步:定义附件实体类

先创建对应附件详情的实体类,注意处理JSON里的下划线命名和可选字段:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true) // 忽略JSON中未定义的字段,避免解析报错
public class AttachmentItem {
    private String ext;
    private Integer height;
    private String md5;
    private String name;
    private String ref;
    private Boolean rotate;
    private Long size;
    private String thumb;
    
    @JsonProperty("thumb_size") // 映射JSON中的下划线字段到Java驼峰命名
    private Integer thumbSize;
    
    private String type;
    private Integer width;

    // 生成所有字段的getter和setter,或者用Lombok的@Data注解简化代码
}

第二步:定义顶层响应类

用Map来接收attachment下的动态键值对:

public class AttachmentResponse {
    private Map<String, AttachmentItem> attachment;

    // getter和setter
    public Map<String, AttachmentItem> getAttachment() {
        return attachment;
    }

    public void setAttachment(Map<String, AttachmentItem> attachment) {
        this.attachment = attachment;
    }
}

第三步:解析JSON

用Jackson的ObjectMapper完成解析,之后就可以遍历Map获取所有附件:

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonParserExample {
    public static void main(String[] args) throws Exception {
        // 你的目标JSON字符串
        String jsonContent = "{ \"attachment\": { \"_2K26Z-mLJmMSRnssLwD0zQ\": { \"ext\": \"jpg\", \"height\": 3024, \"md5\": \"219c226e0070b7367f90e2f1bff1dfc2\", \"name\": \"IMG_1871.jpg\", \"ref\": \"MTUyMTAzNDY5MDUzNElNR18xODcxLmpwZw==\", \"rotate\": true, \"size\": 1514957, \"thumb\": \"thumb_1024_219c226e0070b7367f90e2f1bff1dfc2\", \"thumb_size\": 73119, \"type\": \"image\", \"width\": 4032 }, \"_Q7l14s87UquHcAYoolNCuw\": { \"ext\": \"png\", \"height\": 186, \"md5\": \"75023fd60d59907...\" } } }";

        ObjectMapper objectMapper = new ObjectMapper();
        // 解析JSON到实体类
        AttachmentResponse response = objectMapper.readValue(jsonContent, AttachmentResponse.class);

        // 遍历所有附件,获取随机键和对应的详情
        for (Map.Entry<String, AttachmentItem> entry : response.getAttachment().entrySet()) {
            String randomKey = entry.getKey();
            AttachmentItem item = entry.getValue();
            
            System.out.println("随机键:" + randomKey);
            System.out.println("文件扩展名:" + item.getExt());
            // 按需获取其他字段,比如height、md5等
        }
    }
}

方案二:用@JsonAnySetter注解收集动态键

如果觉得直接用Map不够优雅,可以用Jackson的@JsonAnySetter注解自动将动态键值对存入Map,代码结构更清晰:

修改顶层响应类

import com.fasterxml.jackson.annotation.JsonAnySetter;
import java.util.HashMap;
import java.util.Map;

public class AttachmentResponse {
    private Map<String, AttachmentItem> attachments = new HashMap<>();

    @JsonAnySetter
    public void addAttachment(String key, AttachmentItem item) {
        attachments.put(key, item);
    }

    public Map<String, AttachmentItem> getAttachments() {
        return attachments;
    }
}

之后的解析代码和方案一基本一致,只是获取附件时调用getAttachments()即可。

额外优化建议

  • 如果JSON里的字段都是下划线命名,可以配置ObjectMapper自动转驼峰,省去每个字段加@JsonProperty的麻烦:
    objectMapper.setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategy.SNAKE_CASE);
    
  • 实体类字段可以用Optional类型来处理可选字段,比如private Optional<Integer> height;,这样获取时更安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:42:25