1
是否可以強制Converter(org.springframework.core.convert.converter.Converter)完成json對象映射?在@RequestBody中使用彈簧轉換器
的Json代碼例如:
{
"name": "somename",
"customObject": id
}
其中somename - 串,ID - 整數值
映射到:
@Getter
@Setter
@NoArgConstructor
public class ParentObject{
private String name;
private CustomObject customObject;
}
轉換代碼例如:
@Component
public class CustomObjectConverter implements Converter<String, CustomObject>{
@Autowired
private CustomObjectService customObjectService;
@Override
public CustomObject convert(String arg0) {
Long id = Long.parseLong(arg0);
return customObjectService.findById(id);
}
}
什我想要實現的是將該json映射到將從db嵌套對象中自動獲取的對象。
我認爲這是不是一個好主意,在轉換器內使用數據庫調用。但回答你的問題,你只需要在傑克遜使用ObjectMapper將json字符串轉換爲json對象 – Pragnani
您的評論引起了我的興趣,它可能會脫離主題,但我很好奇從轉換器組件調用服務時出了什麼問題。在這樣的流程中我找不到任何危險點。 – Jarek