Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping JSON into Class Objects

Tags:

json

flutter

dart

I am trying to map my JSON file into a class object, and then update the cards based on the newly received JSON.

My JSON structure is like this

 {
        "$class": "FirstCard",
        "id": "1",
        "description": "I am card number one",
        "Role": "attack",
        "score": 0,
        "tag": [
            "string"
        ],................}

my Class looks like this:

  class CardInfo {
  //Constructor
  String id;
  String description;
  String role;
  int score;

}

How can I map the values in my JSON file into the fields of objects created from CardInfo class?

Update

the following trial prints null at ci.description, does this mean the object was never created ?

const jsonCodec = const JsonCodec
_loadData() async {
  var url = 'myJsonURL';
  var httpClient  = createHttpClient();
  var response =await httpClient.get(url);
  print ("response" + response.body);
  Map cardInfo = jsonCodec.decode(response.body);
  var ci = new CardInfo.fromJson(cardInfo);
  print (ci.description); //prints null
}

Update2

Printing cardInfo gives the following:

{$class: FirstCard, id: 1, description: I am card number one,........}

Note that it resembles the original JSON but without the double quotes on string values.

like image 927
Shady Aziza Avatar asked Jul 19 '17 11:07

Shady Aziza


2 Answers

class CardInfo {
  //Constructor
  String id;
  String description;
  String role;
  int score;

  CardInfo.fromJson(Map json) {
    this.id = json['id'];
    this.description = json['description'];
    this.role = json['Role'];
    this.score = json['score'];
  }
}

var ci = new CardInfo.fromJson(myJson); 

You can use source generation tools like https://github.com/dart-lang/source_gen https://pub.dartlang.org/packages/json_serializable to generate the serialization and deserialization code for you.

If you prefer using immutable classes https://pub.dartlang.org/packages/built_value is a good bet.

like image 133
Günter Zöchbauer Avatar answered Oct 06 '22 23:10

Günter Zöchbauer


If you want to get your JSON from a url do as follows:

import 'dart:convert';

_toObject() async {
  var url = 'YourJSONurl';
  var httpClient  = createHttpClient();
  var response =await httpClient.get(url);
  Map cardInfo = JSON.decode(response.body);
  var ci = new CardInfo.fromJson(cardInfo);
}

Please refer to the main answer if you want to know how to setup your class so that your JSON fields can be mapped to it. It is very helpful.

like image 42
Shady Aziza Avatar answered Oct 07 '22 00:10

Shady Aziza