json_model icon indicating copy to clipboard operation
json_model copied to clipboard

int数组怎么转, "Nums?": "$[]int",这样不行啊

Open keyoumi opened this issue 2 years ago • 2 comments

"Nums?": "$[]num",这样也不行啊

keyoumi avatar Jan 29 '24 08:01 keyoumi

用jsonKey

{
  "@meta": {
    "import": [],
    "comments": {
      "name": "名字",
      "following": "关注",
      "followers": "粉丝",
      "keywords": "标签",
      "age": "年龄"
    },
    "nullable": true,
    "ignore": false
  },
  "@JsonKey(name: 'thisIsApiKey') List<int>?": "thisIsIntList",
  "name": "wendux",
  "following": "$[]user",
  "followers": "$[]user",
  "keywords": "$[]String",
  "age?": 20
}

CurryPaste avatar Jun 20 '24 11:06 CurryPaste

会生成 user.dart

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
  User();

  @JsonKey(name: 'thisIsApiKey') List<int>? thisIsIntList;
  // 名字
  String? name;
  // 关注
  List<User>? following;
  // 粉丝
  List<User>? followers;
  // 标签
  List<String>? keywords;
  // 年龄
  num? age;
  
  factory User.fromJson(Map<String,dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

user.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'user.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

User _$UserFromJson(Map<String, dynamic> json) => User()
  ..thisIsIntList = (json['thisIsApiKey'] as List<dynamic>?)
      ?.map((e) => (e as num).toInt())
      .toList()
  ..name = json['name'] as String?
  ..following = (json['following'] as List<dynamic>?)
      ?.map((e) => User.fromJson(e as Map<String, dynamic>))
      .toList()
  ..followers = (json['followers'] as List<dynamic>?)
      ?.map((e) => User.fromJson(e as Map<String, dynamic>))
      .toList()
  ..keywords =
      (json['keywords'] as List<dynamic>?)?.map((e) => e as String).toList()
  ..age = json['age'] as num?;

Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
      'thisIsApiKey': instance.thisIsIntList,
      'name': instance.name,
      'following': instance.following,
      'followers': instance.followers,
      'keywords': instance.keywords,
      'age': instance.age,
    };

CurryPaste avatar Jun 20 '24 11:06 CurryPaste