假设我有多个DTO,例如:
data class ActionDetailDTO(
@JsonProperty("priority")
val priority: String,
@JsonProperty("reason")
val reason: String
)
data class IntroDTO(
@JsonProperty("name")
val name: String,
@JsonProperty("number")
val number: String
)
我将这些dtos的json存储为字符串, 当我解析他们做这样的事情时:
fun parseStringBasedOnType(action: SomeDTOType) :Any{
val obj = when (action.actionType){
"CREATED" -> objectMapper.readValue(action.actionDetails, ActionDetailDTO::class.java)
"INTRO" -> objectMapper.readValue(action.actionDetails, IntroDTO::class.java)
else -> "hh"
}
return obj
}
这样:
val nn = parseStringBasedOnType(SomeActionObject) //type: CREATED
if(nn.actionType == "CREATED"){
println(nn.reason)
}
这显然不起作用,如何处理?
答案 0 :(得分:0)
您可以使用actionType
方法定义公共接口,也可以转换值:
if(nn is ActionDetailDTO) {
println(nn.reason)
}
如果您打算为其他类型做某事,请使用when
:
when(nn) {
is ActionDetailDTO -> println(nn.reason)
is IntroDTO -> println(nn.number)
}