如何使用Jackson ObjectMapper将含键值对的JSON转为指定Java对象?
实现方案
要实现将JSON中的agents键值对对象转换为List<Agent>(其中Agent的code对应JSON键、name对应JSON值),你需要通过自定义Jackson反序列化器配合ObjectMapper完成转换,具体步骤如下:
1. 编写自定义反序列化器
创建继承自JsonDeserializer<List<Agent>>的类,在deserialize方法中把JSON对象的键值对映射为Agent实例并收集成列表:
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; public class AgentListDeserializer extends JsonDeserializer<List<Agent>> { @Override public List<Agent> deserialize(JsonParser parser, DeserializationContext context) throws IOException { JsonNode node = parser.getCodec().readTree(parser); List<Agent> agents = new ArrayList<>(); // 遍历JSON对象的所有键值对 Iterator<Map.Entry<String, JsonNode>> iterator = node.fields(); while (iterator.hasNext()) { Map.Entry<String, JsonNode> entry = iterator.next(); Agent agent = new Agent(); agent.setCode(entry.getKey()); agent.setName(entry.getValue().asText()); agents.add(agent); } return agents; } }
2. 给Top类的agents字段绑定注解
在Top类的agents字段上添加@JsonDeserialize注解,指定使用上面的自定义反序列化器:
import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.util.List; class Top { private String code; private String type; @JsonDeserialize(using = AgentListDeserializer.class) private List<Agent> agents; // 生成getter、setter方法 public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List<Agent> getAgents() { return agents; } public void setAgents(List<Agent> agents) { this.agents = agents; } } class Agent { private String code; private String name; // 生成getter、setter方法 public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3. 使用ObjectMapper完成转换
直接调用ObjectMapper的readValue方法即可完成JSON到Java对象的转换,无需修改ObjectMapper核心实例:
import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { String json = "{\"code\":\"some code\",\"type\":\"type1\",\"agents\":{\"118023\":\"testname1\",\"124244\":\"testname2\"}}"; ObjectMapper objectMapper = new ObjectMapper(); Top top = objectMapper.readValue(json, Top.class); // 验证转换结果 for (Agent agent : top.getAgents()) { System.out.println("Agent code: " + agent.getCode() + ", name: " + agent.getName()); } } }
关键说明
- 必须用自定义反序列化器:JSON中的
agents是键值对对象结构,而目标Java字段是List<Agent>,Jackson默认无法自动完成这种结构映射,必须通过自定义逻辑处理。 - 无需替换ObjectMapper:所有操作基于原生
ObjectMapper,仅通过注解绑定自定义逻辑即可,完全符合要求。
内容的提问来源于stack exchange,提问作者Srikanth
相关产品推荐
相关产品推荐

