Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

I want to convert JSON data to a generic type in Flutter

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;
  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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't really avoid using Map<string, dynamic>. Because that's the only way you map a JSON into a class object, but if you prefer to Convert a JSON into a T class here is the example. first, create ServiceResult as you do Then create T class for the result

class ServiceResult
{
  T result;
  String message;
  bool hasError;
  bool hasSuccessMessage;
}
class T{
  String yourStringHere;
  String yourAnotherStringHere;
  int yourIntHere;
}

crucial part

ServiceResult.fromJson(Map<String, dynamic> json) {
    message= json['message'];
    hasError= json['has_error'];
    hasSuccessMessage= json['has_success_message'];
    result = json['result'] != null ? new result .fromJson(json['result']) : null;
}
T.fromJson(Map<String, dynamic> json) {
    yourStringHere= json['your_string_here'];
    yourAnotherStringHere= json['your_another_string_here'];
    yourIntHere= json['your_int_here'];
}

bonus: Javier Lecuona create genius tools to convert a JSON into a class object, so you can be lazy like I do :P here: https://javiercbk.github.io/json_to_dart/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...