Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将JSON映射到类对象_Json_Dart_Flutter - Fatal编程技术网

将JSON映射到类对象

将JSON映射到类对象,json,dart,flutter,Json,Dart,Flutter,我试图将我的JSON文件映射到一个类对象中,然后根据新收到的JSON更新卡片 我的JSON结构如下 { "$class": "FirstCard", "id": "1", "description": "I am card number one", "Role": "attack", "score": 0, "tag": [ "string" ],......

我试图将我的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
}
更新2

打印cardInfo提供以下信息:

{$class:FirstCard,id:1,description:I是一号卡,…}

请注意,它类似于原始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); 
您可以使用源代码生成工具,如为您生成序列化和反序列化代码


如果您喜欢使用不可变类,这是一个不错的选择。

如果您想从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);
}

如果您想知道如何设置类,以便将JSON字段映射到该类,请参阅主要答案。这非常有用。

我使用名为
json\u parser
的反射创建了一些有用的库,可在
pub
上找到

您可以将以下内容添加到您的
依赖项中。yaml

dependencies:
  json_parser: 0.1.1
  build_runner: 0.8.3
然后可以使用以下方法解析json:

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

按照
README.md
了解更多说明。

我找到的最佳解决方案是

它可以很容易地将Json转换为dart

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);
}
import'package:json_annotation/json_annotation.dart';
“后置U型g.dart”部分;
@JsonSerializable()
类后模型{
int用户标识;
int-id;
字符串标题;
弦体;
PostModel(this.userId、this.id、this.title、this.body);
factory PostModel.fromJson(Map json)=>\uU$PostModelFromJson(json);
映射到JSON()=>$PostModelToJson(此);
}

此pkg可以帮助您将JSON转换为类实例


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

将依赖项添加到
publispec.yaml

dependencies:
  json_parser: 0.1.1
  build_runner: 0.8.3
依赖项:
json_注释:^4.0.0
开发依赖项:
生成它:^0.2.5
json_可序列化:^4.0.2
创建配置文件
my_classes.yaml

dependencies:
  json_parser: 0.1.1
  build_runner: 0.8.3
---
格式:
名称:build_it
发电机:
名称:build_it:json
---
安全检查:正确
课程:
-姓名:CardInfo
领域:
-{name:id,type:String?}
-{名称:说明,类型:字符串?}
-{name:role,type:String?,jsonKey:{name:role}
-{name:score,type:int?}
-{name:tag,type:List,jsonKey:{defaultValue:[]}
运行生成过程:

dart run build_runner build
生成的代码
my_classes.g.dart

//生成的代码-不要手动修改
导入“package:json_annotation/json_annotation.dart”;
“我的课,g.g.dart”部分;
// **************************************************************************
//build\u it:build\u it:json
// **************************************************************************
@JsonSerializable()
CardInfo类{
卡迪尼奥(
{this.id,this.description,this.role,this.score,需要this.tag});
///从JSON表示创建“CardInfo”的实例
factory CardInfo.fromJson(映射json)=>
_$cardinforomjson(json);
字符串?id;
字符串描述;
@JsonKey(名称:“角色”)
字符串?角色;
积分;
@JsonKey(默认值:[])
列表标签;
///返回“CardInfo”实例的JSON表示形式。
映射到JSON()=>$CardInfoToJson(此);
}

现在您可以使用它们了。

请查看我文章中更新的部分,我尝试在对象ci中打印一个字段,但得到的结果是空的。
打印什么(cardInfo)打印?现在可以工作了,我在映射到JSON值的键中有一个小的打字错误,非常感谢您的帮助!它是否与dart 2.0配合使用?当前的Dart SDK版本是2.1.0-dev.1.0.flatter-ccb16f7282。如果您使用的是最新版本,则是!)错误:依赖于json语法分析器>=0.0.2=1.19.0使用
json语法分析器:^0.1.6
相同错误:因为json语法分析器>=0.1.4依赖于构建运行程序^0.10.1+1,而应用程序依赖于构建运行程序0.8.3,所以json语法分析器>=0.1.4是禁止的。所以,因为应用程序依赖于json_解析器^0.1.6,所以版本解析失败。