How to run a code-generator on the top of another code-generator?

后端 未结 3 1172
遥遥无期
遥遥无期 2021-02-13 04:26

Using the source_gen stack to make a code generator, how can I make a generator that generates code that would be the input of another generator (more specifically json_se

3条回答
  •  情歌与酒
    2021-02-13 04:59

    You can decode the JSON by calling the jsonDecode() function, with the JSON string as the method argument.

    Map user = jsonDecode(jsonString);
    
    print('Howdy, ${user['name']}!');
    print('We sent the verification link to ${user['email']}.');
    

    Now, Use the User.fromJson() constructor, for constructing a new User instance from a map structure and a toJson() method, which converts a User instance into a map.

    employee.dart

    class Employee {
      final String name;
      final String id;
    
      Employee(this.name, this.id);
    
      Employee.fromJson(Map json)
          : name = json['name'],
            id = json['id'];
    
      Map toJson() =>
        {
          'name': name,
          'id': id,
        };
    }
    

    json_serializable is an automated source code generator that generates the JSON serialization boilerplate for you.

    You need one regular dependency, and two dev dependencies to include json_serializable in your project.

    dependencies:
      json_annotation: ^0.2.3
    
    dev_dependencies:
      build_runner: ^0.8.0
      json_serializable: ^0.5.0
    

    For more details on JSON serialization you can refer here

    you can also use the Smoke library.

    It's a subset of the Mirrors functionality but has both a Mirrors-based and a Codegen-based implementation. It's written by the PolymerDart team, so it's as close to "Official" as we're going to get.

    While developing, it'll use the Mirrors-based encoding/decoding; but for publishing you can create a small transformer that will generate code.

    Seth Ladd created a code sample here, which I extended slightly to support child-objects:

提交回复
热议问题