如何将JSON中的details转为ArrayList<Details>集合?
解决方案
方案一:让Spring自动完成反序列化(推荐)
直接把控制器的入参改成NewQuote,Spring自带的Jackson会自动把前端传的JSON转换成实体对象,包括嵌套的Details列表,完全不用手动处理JSON:
修改后的控制器代码
@PostMapping(value = "/save-quote", produces = MediaType.APPLICATION_JSON_VALUE) public void saveQuote(@RequestBody NewQuote newQuote) { newQuoteService.saveQuote(newQuote); }
修改服务层代码
public void saveQuote(NewQuote newQuote) { newQuoteRepository.save(newQuote); }
注意:实体类需要补充必要结构
JPA和Jackson反序列化都要求有无参构造,同时要给所有字段添加getter/setter:
@Entity public class NewQuote { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String description; @ElementCollection(targetClass = Details.class) private List<Details> details = new ArrayList<>(); // 必须添加无参构造 public NewQuote() {} public NewQuote(String description, ArrayList<Details> details) { this.description = description; this.details = details; } // 所有字段的getter和setter public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<Details> getDetails() { return details; } public void setDetails(List<Details> details) { this.details = details; } }
Details类补充getter/setter即可:
@Embeddable public class Details { private String description; private String label; public Details(String description, String label) { this.description = description; this.label = label; } public Details() {} // getter和setter public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } }
方案二:如果必须用Map接收(不推荐)
要是因为特殊场景只能用Map<String, String>接收,就用Jackson的ObjectMapper把details对应的JSON字符串转成List<Details>:
修改后的服务层代码
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import java.util.ArrayList; // 注入Spring自动配置的ObjectMapper private final ObjectMapper objectMapper; public YourServiceClass(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } public void saveQuote(Map<String, String> data) { String description = data.get("description"); String detailsJson = data.get("details"); try { // 将JSON字符串转成List<Details> List<Details> details = objectMapper.readValue(detailsJson, new TypeReference<List<Details>>() {}); NewQuote newQuote = new NewQuote(description, new ArrayList<>(details)); newQuoteRepository.save(newQuote); } catch (Exception e) { // 处理JSON解析异常,比如抛自定义异常或打日志 throw new RuntimeException("解析details失败", e); } }
内容的提问来源于stack exchange,提问作者xRay
相关产品推荐
相关产品推荐

