Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Generic json serializer with Dart

I'm new in Flutter and trying to implement something similar to Swift generic decodable, like below:

struct ParentJson<T>: Decodable where T: Decodable

After hours of searching, I found out there are 2 libraries serving same purpose built_value and json_annotation and a sentence says, Dart does not do generic type erasure.


I'm trying to parse json below:

{ 
    "status": 200,
    "message": "This message", 
    "data": { 
        "uid": "tested",
        "email": "[email protected]",
        "name": "test"
    } 
}

In this case data can be different and this is the place I want to make data generic.


With built_value generic example T have to be specified as specifiedType in addBuilderFactory as David mentioned here.

And this is an official example with json_annotation.

Both ways totally violates the concepts of generic, since I need to declare all different types in parent classes or serializers, instead of simply write a code like this:

Parent<User> user = Parent<User>.deserialize(json.decode(jsonString))

So my question from Dart and Flutter experts is,

  • Is this a Dart language limitation?
  • Is there any way to implement generic value for parsing json without violating generic concept?
like image 565
Nik Avatar asked Jan 21 '26 09:01

Nik


1 Answers

Actually, there is a solution for your use case. It's a https://github.com/k-paxian/dart-json-mapper library.

I'm pretty sure you are looking for something like this. You'll find working unit tests illustrating your use case.

like image 152
Alexander Mazuruk Avatar answered Jan 23 '26 01:01

Alexander Mazuruk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!