google / json_serializable.dart

Generates utilities to aid in serializing to/from JSON.
https://pub.dev/packages/json_serializable
BSD 3-Clause "New" or "Revised" License
1.55k stars 394 forks source link

I want to convert JSON data to a generic type in Flutter. #779

Open ahmeteerdogan opened 3 years ago

ahmeteerdogan commented 3 years ago

Hello everyone I'm new to Flutter. I want to convert JSON data to a generic type in Flutter.

class ServiceResult<T>
{
  T result;
  String message;
  String errorCode;
  bool hasError;
  bool hasSuccessMessage;
}

I can use Map<string, dynamic> But I don't want to use it dynamically. I want to cast to T. I have always seen dynamic uses in my research. Is there a method that I can cast directly to T?

I get the following error from the code line below. _type 'InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'UserDto' in type cast

ServiceResult<T> fromJson<T>(
    Map<String, dynamic> json
    ) {
  return ServiceResult<T>()
    ..message = json['message'] as String
    ..errorCode = json['errorCode'] as String
    ..hasError = json['hasError'] as bool
    ..hasSuccessMessage = json['hasSuccessMessage'] as bool
    ..result = json['result'] as T;
}
yendangn commented 3 years ago

You can get example here: https://github.com/google/json_serializable.dart/blob/master/example/lib/generic_response_class_example.dart

Fl0r14nJ commented 3 years ago

ello it seems that this feature is not available. See here: https://stackoverflow.com/questions/53709688/dart-generic-which-has-fromjson-constructor

Fl0r14nJ commented 3 years ago

Hello I have found a package that allows this see here: https://pub.dev/packages/simple_json It's actually pretty simple. Here have a sample code


import 'package:simple_json_mapper/simple_json_mapper.dart';

@JObj()
class EndpointInfo{
  final String identifier;
  final String version;
  final String? commitRef;

  const EndpointInfo({required this.identifier, required this.version, this.commitRef});
}

  Future<T?> endpointGet<T>(String endpoint) async {
    Uri url = Uri.parse(this.homeServer + endpoint);
    Response response = await get(url);

    final result = JsonMapper.deserialize<T>(response.body);

    return result;
  }
# dart
pub get
pub run build_runner watch
# flutter
flutter pub get
flutter packages pub run build_runner watch