Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Convert List as Map Entry for JSON Encoding

Tags:

dart

I asked a question before about Dart encoding/decoding to JSON, however, the libraries that were suggested were not complete and I decided to manually handle that.

The objective is to convert these objects to a map.

class Parent extends Object {
   int id;
   String name;
   List<Child> listChild = new List<Child>();
   Map toMap() => {"id":id, "name":name, "listChild":listChild};
}

class Child extends Object {
   int id;
   String childName;
   Map toMap() => {"id":id, "childName":childName};   
}

When doing

print(JSON.encode(parent.toMap()));

I am seeing it go here, any suggestion how to make this work?

if (!stringifyJsonValue(object)) {
  checkCycle(object);
  try {
    var customJson = _toEncodable(object);
    if (!stringifyJsonValue(customJson)) {
      throw new JsonUnsupportedObjectError(object);
    }
    _removeSeen(object);
  } catch (e) {
    throw new JsonUnsupportedObjectError(object, cause : e);
  }
}
}
like image 566
javapadawan Avatar asked Sep 13 '14 20:09

javapadawan


Video Answer


2 Answers

Map toMap() => {"id":id, "name":name: "listChild": listChild.map((c) => c.toJson().toList())};

is valid for JSON.

import 'dart:convert' show JSON;

...

String json = JSON.encode(toMap());

You can also use the toEncodeable callback - see How to convert DateTime object to json

like image 118
Günter Zöchbauer Avatar answered Nov 04 '22 03:11

Günter Zöchbauer


If your class structure does not contain's any inner class then follow

class Data{

  String name;
  String type;

  Map<String, dynamic> toJson() => {
        'name': name,
        'type': type
      };
}

If your class uses inner class structure

class QuestionTag {
  String name;
  List<SubTags> listSubTags;

  Map<String, dynamic> toJson() => {
        'name': name,
        'listSubTags': listSubTags.map((tag) => tag.toJson()).toList()
      };
}

class SubTags {
  String tagName;
  String tagDesc;

  SubTags(this.tagName, this.tagDesc);

  Map<String, dynamic> toJson() => {
        'tagName': tagName,
        'tagDesc': tagDesc,
      };
}
like image 44
Dhanaji Yadav Avatar answered Nov 04 '22 02:11

Dhanaji Yadav