【问题标题】:Spring Boot and Kotlin - How to validate a JSON objectSpring Boot 和 Kotlin - 如何验证 JSON 对象
【发布时间】:2019-12-04 12:27:48
【问题描述】:

我在 Kotlin 中使用 Spring Boot。

我正在接收一些 JSON 字符串,并使用 ObjectMapper 对其进行解析,但我想验证它是否具有模型中的所有内容 - 即 ids3FilePath 不是空白或缺失。

所以这是我要验证的模型:

@JsonIgnoreProperties(ignoreUnknown = true)
class MyModel {
    var id : String = ""
    var s3FilePath : String = ""
}

这是我使用该模型的地方:

class FirstMessage {
    fun create(newMessage: String) : String {

        val objectMapper = ObjectMapper()
        val parsedMap : MyModel = objectMapper.readValue(newMessage, MyModel::class.java)

        val result = MyModel()
        result.id = parsedMap.id
        result.s3FilePath = parsedMap.s3FilePath

        return objectMapper.writeValueAsString(result)
    }
}

最后我有这个测试,我想验证一个异常:

@Test
    fun incompleteDataReturnsException() {
        var input = """{"missing": "parts"}"""

        // FirstMessage().create(input) // Will make some assertion here here
}

任何帮助将不胜感激。我刚刚开始使用 Spring 及其相当“强烈”。

谢谢。

附言如果创建该模型错误/有更好的方法,请告诉我。我有点不确定这是否正确。

【问题讨论】:

    标签: spring spring-boot kotlin


    【解决方案1】:

    您应该为模型使用数据类。另外,使用 kotlin jacksonObjectMapper() 而不是 ObjectMapper()。标准 ObjectMapper 在 Kotlin 中不起作用。或者从 Spring 上下文中注入 ObjectMapper。在依赖项中添加"com.fasterxml.jackson.module:jackson-module-kotlin"

    @JsonIgnoreProperties(ignoreUnknown = true)
    data class MyModel (
    val id : String,
    val s3FilePath : String
    )
    
    import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
    import com.fasterxml.jackson.module.kotlin.readValue
    class FirstMessage {
    fun create(newMessage: String) : String {
    
        val parsedMap : MyModel = jacksonObjectMapper().readValue(newMessage)
    
        return jacksonObjectMapper().writeValueAsString(parsedMap)
    }
    }
    
    class FirstMessageTest {
    
    @Test
    fun incompleteDataReturnsException() {
        val input = """{"missing": "parts"}"""
    
       assertThrows (MissingKotlinParameterException::class.java
    {FirstMessage().create(input)} // Will make some assertion here here
    }
    
    @Test
    fun `Should parse`() {
        val input = """{"id":"id",
            "missing": "parts",
            "s3FilePath":"somePath"}"""
    
        FirstMessage().create(input) // Will make some assertion here here
    }
    }
    

    【讨论】:

    • 谢谢 - 我怎样才能验证空字符串?例如,错误是s3FilePath""
    • 在 Spring 应用程序中,您可以简单地为字段添加注释 - @NotEmpty,并在服务中为类添加#@Validated 和在方法中添加#@Valid,例如,fun save(#@Valid myclass:我的课)。但是对于您的测试,我认为这会有所帮助stackoverflow.com/questions/27063892/…
    【解决方案2】:

    如果我对您的问题的理解正确,您只想检查您的所需属性是否已设置。因此,我建议您在使用以下内容解析字符串后检查该属性:

    class FirstMessage {
        fun create(newMessage: String) : String {
    
            val objectMapper = ObjectMapper()
    
            // validation 1: your input is valid JSON
            val parsedMap : MyModel = objectMapper.readValue(newMessage, MyModel::class.java) 
    
            // validation 2: check that your properties are set
            if(parsedMap.id.isNullOrEmpty() || 
               parsedMap.s3FilePath.isNullOrEmpty())
            {
                throw IllegalArgumentException("Invalid input")
            }
    
            val result = MyModel()
            result.id = parsedMap.id
            result.s3FilePath = parsedMap.s3FilePath
    
            return objectMapper.writeValueAsString(result)
        }
    }
    

    根据范围,一个更好的解决方案是一个新的注释,如@NotEmpty,你在你的目标类的属性上设置这是必需的,并且有一个通用的解析器函数来验证你解析的对象上的所有注释字段和抛出一个更好的异常,准确说明缺少哪些字段。

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 2018-08-08
      • 2020-11-22
      • 2014-01-09
      • 1970-01-01
      • 2018-12-05
      • 2020-02-17
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多