Home > Blockchain >  Is there any alternative of converting the JSON response into a custom Dart object?
Is there any alternative of converting the JSON response into a custom Dart object?

Time:08-09

I am new to flutter and dart and making an application with nodejs backend with MongoDB as my database. When requesting data from flutter using HTTP package I noticed I have to convert the JSON to a custom Dart object.

I referred to the official document

Everything is working fine, but I find this conversion of data a very long process and unnecessary line of code if I have many different pages with a different types of data coming from the backend.

Is there any quick or better way to accomplish this? Thank you

CodePudding user response:

Dart is an Object Oriented Programming language.

That's why the official documentation is talking about converting your Json into a Dart Object :)
You could achieve the same things by having your Jsons as Maps<String, dynamic> instead of converting it to Dart Objects, but at the cost of an unnecessary complex code.

If you have a lot of models to use, you can use a library generating the parsing methods for you like json_serializable thank to some annotation processing, or even freezed which is generating even more useful methods.

Basic example of json_serializable :

import 'package:json_annotation/json_annotation.dart';

part 'user_agenda.g.dart';

@JsonSerializable()
class UserAgenda {
  String? uid;
  String? name;
  String? imgUrl;
  int? nextDate;

  UserAgenda() {}

  factory UserAgenda.fromJson(Map<String, dynamic> json) => _$UserAgendaFromJson(json);

  Map<String, dynamic> toJson() => _$UserAgendaToJson(this);

}

Personal opinion : in your case, go for json_serializable. Freezed may be overkill, and playing with the Maps will shortly become a real pain to maintain.

CodePudding user response:

For Converting JSON Response to Dart object you should use https://app.quicktype.io

Select Language as Dart. Please note that generated code will not a null safe code. so you have to take care of it.

CodePudding user response:

You don't need to convert the response to the Dart objects you made before. Just use

  Map<String, dynamic> answer = jsonDecode(response.body);

Then you can access any value by it's key like this:

 var x = answer['key1'][0]['key2'];

But You need to know each time the structure of JSON.

  • Related