Home > Blockchain >  jsonEncode throwing exceptions encoding a simple class
jsonEncode throwing exceptions encoding a simple class

Time:07-18

Friends

I have a simple Dart class that cannot be encoded into JSON.

The output of the following code prints out to the console

flutter: Converting object to an encodable object failed: Instance of 'TestJsonConversion'

class TestJsonConversion {
  String testString = "123245abcde";
  int testIneger = 1234;
}

void main() {
  var testJsonConversion = TestJsonConversion();
  try {
    var testString = jsonEncode(testJsonConversion);
    // ignore: avoid_print
    print(testString);
  }catch(e){
    // ignore: avoid_print
    print(e.toString());
  }
  runApp(const MyApp());
}

This is the default application generated by Visual Studio with just these lines added.

CodePudding user response:

You cannot encode an instance of a user class with the built-in jsonEncode. These are things you can encode by default: "a number, boolean, string, null, list or a map with string keys". For this class to encode, you'd have to define a .toJson method on it, and I don't see one there.

CodePudding user response:

The class has no constructors and tojson . Try this

class TestJsonConversion {
  final String testString;
  final int testInteger;

 TestJsonConversion(this.testString, this.testInteger);

  TestJsonConversion.fromJson(Map<String, dynamic> json)
      : testString = json['trstString'],
        testInteger = json['testInteger'];

  Map<String, dynamic> toJson() => {
        'testString': testString,
        'testInteger': testInteger,
      };
}

And when you create an instance

var testJsonConversion = TestJsonConversion(testString: 'abc', testInteger: 123);
print(json.encode(testJsonConversion);
  • Related