https://kotlinlang.org logo
#serialization
Title
# serialization
r

rrader

12/26/2018, 2:25 PM
How validation is done? for example we need to check that a property length should not be more than 100 characters
s

sandwwraith

12/26/2018, 2:25 PM
You can do it in
init
blocks which are executed after deserialization
r

rrader

12/26/2018, 2:28 PM
usually on deserialization we want to collect all validation errors and return them in response, in this case validation about not null and other validation will be separated, so we can not collect all errors at once is this correct?
s

sandwwraith

12/26/2018, 2:29 PM
not-null validation is performed automatically by the framework
r

rrader

12/26/2018, 2:32 PM
I mean for example we have a class
class Data(val name: String, val age: Int, val email: String)
when we send a json
{"email": "<mailto:xyz@xyz.com|xyz@xyz.com>", "name": "A"}
we should return a response where to indicate that
age
can not be null and
name
size must be greater than 2 Is this possible?
s

sandwwraith

12/26/2018, 2:35 PM
I think yes. If you throw, say
ValidationException
from init block of
Data
, you can write
Copy code
try {
   deserialize(request)
} catch (e: MissingFieldException) {
...
} catch (e: ValidationException) {
...
}
r

rrader

12/26/2018, 2:36 PM
but how we will pass the constructor if we do not have value for
age
field?
s

sandwwraith

12/26/2018, 2:37 PM
Ah, I got it. Yes, you will get only first exception in this case, unfortunately
r

rrader

12/26/2018, 2:38 PM
Oh, bad 😞 BTW, what do you think about to do validation before object creation? We had an interesting thread today on similar issue https://kotlinlang.slack.com/conversation/C0B8Q383C/p1545658515001900
s

sandwwraith

12/26/2018, 2:42 PM
It would be complicated to design, because validation is natural to do in
init
block, and its execution likely requires already constructed object...
4 Views