将 JSON 映射到 Class 对象

Mapping JSON into Class Objects

我正在尝试将我的 JSON 文件映射到 class 对象,然后根据新收到的 JSON.

更新卡片

我的JSON结构是这样的

 {
        "$class": "FirstCard",
        "id": "1",
        "description": "I am card number one",
        "Role": "attack",
        "score": 0,
        "tag": [
            "string"
        ],................}

我的 Class 看起来像这样:

  class CardInfo {
  //Constructor
  String id;
  String description;
  String role;
  int score;

}

如何将我的 JSON 文件中的值映射到从 CardInfo class 创建的对象的字段中?

更新

以下试验在 ci.description 处打印 null,这是否意味着该对象从未创建?

const jsonCodec = const JsonCodec
_loadData() async {
  var url = 'myJsonURL';
  var httpClient  = createHttpClient();
  var response =await httpClient.get(url);
  print ("response" + response.body);
  Map cardInfo = jsonCodec.decode(response.body);
  var ci = new CardInfo.fromJson(cardInfo);
  print (ci.description); //prints null
}

更新2

打印 cardInfo 给出以下内容:

{$class: FirstCard, id: 1, description: I am card number one,........}

请注意,它类似于原始的 JSON,但字符串值上没有双引号。

class CardInfo {
  //Constructor
  String id;
  String description;
  String role;
  int score;

  CardInfo.fromJson(Map json) {
    this.id = json['id'];
    this.description = json['description'];
    this.role = json['Role'];
    this.score = json['score'];
  }
}

var ci = new CardInfo.fromJson(myJson); 

您可以使用 https://github.com/dart-lang/source_gen https://pub.dartlang.org/packages/json_serializable 等源代码生成工具为您生成序列化和反序列化代码。

如果您更喜欢使用不可变 类 https://pub.dartlang.org/packages/built_value 是个不错的选择。

如果您想从 url 中获取 JSON,请执行以下操作:

import 'dart:convert';

_toObject() async {
  var url = 'YourJSONurl';
  var httpClient  = createHttpClient();
  var response =await httpClient.get(url);
  Map cardInfo = JSON.decode(response.body);
  var ci = new CardInfo.fromJson(cardInfo);
}

如果您想知道如何设置您的 class 以便您的 JSON 字段可以映射到它,请参阅主要答案。很有帮助。

我为此使用称为 json_parser 的反射创建了一些有用的库,可在 pub.

https://github.com/gi097/json_parser

您可以将以下内容添加到您的dependencies.yaml

dependencies:
  json_parser: 0.1.1
  build_runner: 0.8.3

然后 json 可以被解析为:

DataClass instance = JsonParser.parseJson<DataClass>(json);

按照 README.md 获取更多说明。

我找到的最佳解决方案是 this medium post

这很容易将 Json 转换为飞镖

import 'package:json_annotation/json_annotation.dart';

part 'post_model.g.dart';

@JsonSerializable()
class PostModel {
  int userId;
  int id;
  String title;
  String body;
  PostModel(this.userId, this.id, this.title, this.body);
  factory PostModel.fromJson(Map<String, dynamic> json) => _$PostModelFromJson(json);
  Map<String, dynamic> toJson() => _$PostModelToJson(this);
}

此 pkg 可以帮助您将 JSON 转换为 class 实例。 https://www.npmjs.com/package/class-converter

import { property, toClass } from 'class-convert';

class UserModel {
  @property('i')
  id: number;

  @property()
  name: string;
}

const userRaw = {
  i: 1234,
  name: 'name',
};

// use toClass to convert plain object to class
const userModel = toClass(userRaw, UserModel);
// you will get a class, just like below one
{
  id: 1234,
  name: 'name',
}

如果您不想手动创建它们,您可以生成它们。

添加依赖到pubspec.yaml:

dependencies:
  json_annotation: ^4.0.0
dev_dependencies:
  build_it: ^0.2.5
  json_serializable: ^4.0.2

创建配置文件my_classes.yaml:

---
format:
  name: build_it
  generator:
    name: build_it:json
---

checkNullSafety: true

classes:
- name: CardInfo
  fields:
  - { name: id, type: String? }
  - { name: description, type: String? }
  - { name: role, type: String?, jsonKey: { name: Role } }
  - { name: score, type: int? }
  - { name: tag, type: List<String>, jsonKey: { defaultValue: [] } }

运行 构建过程:

dart run build_runner build

生成代码my_classes.g.dart:

// GENERATED CODE - DO NOT MODIFY BY HAND

import 'package:json_annotation/json_annotation.dart';

part 'my_classes.g.g.dart';

// **************************************************************************
// build_it: build_it:json
// **************************************************************************

@JsonSerializable()
class CardInfo {
  CardInfo(
      {this.id, this.description, this.role, this.score, required this.tag});

  /// Creates an instance of 'CardInfo' from a JSON representation
  factory CardInfo.fromJson(Map<String, dynamic> json) =>
      _$CardInfoFromJson(json);

  String? id;

  String? description;

  @JsonKey(name: 'Role')
  String? role;

  int? score;

  @JsonKey(defaultValue: [])
  List<String> tag;

  /// Returns a JSON representation of the 'CardInfo' instance.
  Map<String, dynamic> toJson() => _$CardInfoToJson(this);
}

现在您可以使用它们了。