Class structure for formatting JSON in Dart

I have some classes in Dart and I would like to get a JSON formatted representation.

For example, I have these classes:

class A {
  String a1;
  num a2;
  List<B> bs;
}

class B {
  String b1;
  num b2;
}

      

The JSON formatted object A should look like this:

{
  "a1": "value",
  "a2": 42,
  "bs": [
    {
      "b1": "any value",
      "b2": 13
    },
    {
      "b1": "another value",
      "b2": 0
    }
  ]
}

      

I have looked at some packages in the pub repository but could not find one that suits my needs. I may have missed the correct one.

+3


source to share


1 answer


If those classes have serialization and deserialization, but just don't format JSON, then you can take JSON and decode / encode with a package dart:convert

and pass in the indentation string.

see https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-convert.JsonEncoder#id_JsonEncoder-withIndent



import 'dart:convert' show JSON, JsonEncoder;

...

String json = jsonFromSerializationLib();

print(new JsonEncoder.withIndent('  ').convert(JSON.decode(j)));

      

+4


source







All Articles