Home > Software engineering >  How to serialize any dart object into json?
How to serialize any dart object into json?

Time:09-28

I want to serialize any object into a json string.

For example the PurchaseDetails object I receive after a successful purchase.

It has the following structure:

/// Represents the transaction details of a purchase.
class PurchaseDetails {
  PurchaseDetails({
    this.purchaseID,
    required this.productID,
    required this.verificationData,
    required this.transactionDate,
    required this.status,
  });

  final String? purchaseID;

  final String productID;

  final PurchaseVerificationData verificationData;

  final String? transactionDate;

  PurchaseStatus status;

  IAPError? error;

  bool pendingCompletePurchase = false;
}

Our Back End have requested this output as a JSON and I just need a quick way to parse it.

Is there such a way, and if not, what is best practice when serializing classes from a third party library?

CodePudding user response:

You can simply write custom function which returns string which can be serialized in json like:

import 'dart:convert';

void main() {
  var c = MyClass();

  print(jsonDecode(c.toString())); // <- here is your json
}

class MyClass {
  String name = "Mark";
  int age = 25;

   @override
  String toString() {
    return '{"name": "$name", "age": "$age"}';
  }
}

CodePudding user response:

You could also use Json Serializable, which is a dart package which uses meta-programming to build and handle the serialization code behind the scenes.

You can define which properties to save, which keys to use, and you can also provide custom conversion callbacks and decide whether to serialize null values and much more.

  • Related