0

Is there some way to cast double value from json to int field using json_serializable for code generation? Maybe some annotation? Couldn't find anything like this myself yet.

From json like this

{
  "number": 1.0,
  ...
}

To class like this

class MyClass {
  final int number;
  ...
}

1 Answers1

1

You can use some vsCode or Android Studio extension or map key to class

Like

import 'dart:convert';

SampleClass sampleClassFromJson(String str) => SampleClass.fromJson(json.decode(str));

String sampleClassToJson(SampleClass data) => json.encode(data.toJson());

class SampleClass {
    SampleClass({
        this.number,
    });

    final int number;

    factory SampleClass.fromJson(Map<String, dynamic> json) => SampleClass(
        number: json["number"] == null ? null : json["number"],
    );

    Map<String, dynamic> toJson() => {
        "number": number == null ? null : number,
    };
} 

Most of time im using https://app.quicktype.io this site generating code with minimal modification

harsha.kuruwita
  • 1,315
  • 12
  • 21