Valeriy K.
Valeriy K.

Reputation: 2904

How properly verify type when JSON have only string values

I have an enum with types:

enum class DataType {
    BOOLEAN,
    DOUBLE,
    STRING,
    TIMESTAMP
}

and data class:

data class Entity(
    @Id
    val id: UUID,

    val name: String,
    val properties: List<Property>
)

data class Property(
    val name: String,
    val value: String
)

I have class EntityType which defines properties names and type for every property:

data class EntityType(
    @Id
    val id: UUID,

    val name: String,
    val properties: List<PropertyDefinition>
)

data class PropertyDefinition(
    val name: String,
    val dataType: DataType
)

Each entity which I want to save must-have properties in according with it's EntityType. I want to verify each Property in the Entity properties. I do next:

val entityPropertiesMap = entity.properties.map { Pair(it.name, it) }.toMap()

entityTypeProperties.forEach {
    try {
        when (it.dataType) {
            DataType.BOOLEAN -> checkBoolean(property.value)
            DataType.DOUBLE -> property.value.toDouble()
            DataType.TIMESTAMP -> Instant.parse(property.value)
            DataType.STRING -> if (!property.value.matches(Regex("[a-zA-Z0-9-_.]+"))) {
                throw WrongPropertyValuePatternException("Entity property value '${property.value}' does not match with the pattern [a-zA-Z0-9-_.]+")
            }
        }
    } catch (e: Exception) {
        when (e) {
             is NumberFormatException, is DateTimeParseException, is WrongBooleanFormatException ->
                  throw EntityPropertyCastException("Property '${property.name}' with value '${property.value}' can't be casted to ${it.dataType}.")
             is WrongPropertyValuePatternException -> throw e
             else -> throw e
        }
    }
}

As you see I'm trying to parse values and if I get an error I catch Exception. I can't write

DataType.DOUBLE -> if (!(property.value is Double)) throw SomeMyException("...")

because property.value is always String. How I can verify types without catching parsing exception? Or it is normal practice do as I did?

Upvotes: 0

Views: 46

Answers (1)

jpganz18
jpganz18

Reputation: 5858

Since it is a string and that means you need to convert it to double / or other value. There is no way to know it beforehand without having a possible exception to handle. Therefore, answering your question, use a try/catch is a common practice when converting from strings to numbers.

(plus, you dont need that line is WrongPropertyValuePatternException -> throw e because later you basically throw e anyways)

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-double.html

Upvotes: 1

Related Questions