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

如何用Jackson序列化/反序列化含随机键的JSON与POJO

解决动态随机键JSON的Jackson反序列化与序列化问题

错误原因

你的JSON顶层直接是动态随机键(如random1、nextRandom500)与用户对象的映射,但你的UserResponse类仅定义了users属性,Jackson会将JSON中的每个随机键视为UserResponse的字段,而类中不存在这些字段,因此抛出UnrecognizedPropertyException。

解决方案

方案一:直接使用Map<String, User>(最简方案)

不需要外层UserResponse类,直接将JSON反序列化为Map<String, User>,完全匹配JSON结构:

反序列化代码

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

// 初始化ObjectMapper
ObjectMapper mapper = new ObjectMapper();
// 反序列化JSON字符串
String jsonString = "你的目标JSON字符串";
Map<String, UserResponse.User> userMap = mapper.readValue(
    jsonString,
    new TypeReference<Map<String, UserResponse.User>>() {}
);

序列化代码

// 将Map序列化为目标结构的JSON
String jsonOutput = mapper.writeValueAsString(userMap);

方案二:修改UserResponse类,使用@JsonAnySetter/@JsonAnyGetter

如果需要保留外层UserResponse类,通过Jackson的注解处理动态字段:

修改后的UserResponse类

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.HashMap;
import java.util.Map;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

@Data
@SuperBuilder(toBuilder=true)
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserResponse {
    private Map<String, User> users = new HashMap<>();

    // 反序列化时,所有未知属性自动存入users Map
    @JsonAnySetter
    public void addUser(String key, User user) {
        users.put(key, user);
    }

    // 序列化时,将users Map的键值对作为顶层属性输出
    @JsonAnyGetter
    public Map<String, User> getUsers() {
        return users;
    }

    @Data
    @SuperBuilder(toBuilder=true)
    @NoArgsConstructor
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public static class User {
        private String name;
        private String lastName;
    }
}

反序列化与序列化代码

// 反序列化
UserResponse response = mapper.readValue(jsonString, UserResponse.class);

// 序列化
String jsonOutput = mapper.writeValueAsString(response);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:10:58