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 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.