Validating Json in Dart JsonSerializable and Freezed

89 Views Asked by At

I'm using Freezed to create data classes, and to de-serialized them from a json (with the integration with JsonSerializable). But sometimes the json are incomplete, and the fromJson method do not validate the json. So it throws a _TypeError error that I cannot catch.

There is a way to automatically validate the json? I could use Json schema to manually validate it, but want to know if there is an automatic way first.

1

There are 1 best solutions below

0
perojas3 On

@OMi Shah helped me with his comments.

My problem was I was using making a unit tests where a parsing fails with a json with a wrong schema. But I was testing in wrong.

I searched online, and read that only exceptions can be catch, no error, and this was a weird type of error _TypeError. That was wrong, you can actually catch errors with try and catch.

And this is the way of unit test it:

expect(
  () => FreezedClass.fromJson({"": ""}),
  throwsA(const TypeMatcher<TypeError>())
);

Thanks a lot.