我正在尝试将我的JSON文件映射到类对象,然后根据新收到的JSON更新卡片。
我的JSON结构就像这样
{
"$class": "FirstCard",
"id": "1",
"description": "I am card number one",
"Role": "attack",
"score": 0,
"tag": [
"string"
],................}
我的班级看起来像这样:
class CardInfo {
//Constructor
String id;
String description;
String role;
int score;
}
如何将JSON文件中的值映射到从CardInfo类创建的对象的字段中?
更新
以下试验在 ci.description 处打印为空,这是否意味着该对象从未创建过?
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
}
Update2
打印cardInfo提供以下内容:
{$ class:FirstCard,id:1,说明:我是卡号,........}
请注意,它类似于原始JSON,但没有字符串值的双引号。
答案 0 :(得分:7)
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是一个不错的选择。
答案 1 :(得分:1)
如果您想从网址获取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);
}
如果您想知道如何设置类,请参考主答案,以便将JSON字段映射到它。这非常有帮助。
答案 2 :(得分:1)
我找到的最佳解决方案是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);
}
答案 3 :(得分:0)
我使用名为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
以获得更多说明。
答案 4 :(得分:0)
此pkg可以帮助您将JSON转换为类实例。 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',
}
答案 5 :(得分:0)
如果您不想手动创建它们,可以生成它们。
向 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);
}
现在您可以使用它们了。