在Flutter中解析JSON会导致对象字段的值为NULL

时间:2019-10-09 21:52:36

标签: json flutter dart

我具有以下结构的JSON文件:

[
 {
  "key1":"value1",
  "key2":"value2",
  "key3":"value3",
  "key4":"value4",
 },
 {
  "key1":"value1",
  "key2":"value2",
  "key3":"value3",
  "key4":"value4",
 }
]

我通过HTTP呼叫获得。我尝试将此JSON解析为抖动对象。因此,我写了一堂课:

class Foo {
 List<Model> modelsAsJson;

 Foo({this.modelsAsJson});

 Foo.fromJson(List<dynamic> jsonData) {
  modelsAsJson = jsonData.map((listItem) => Model.fromJson(listItem)).toList();
  Foo(modelsAsJson: modelsAsJson);
 }
}

我还为Model写了另一个类:

class Model {
 String value1;
 String value2;
 String value3;
 String value4;

 Model({this.value1, this.value2, this.value3, this.value4});

 Model.fromJson(Map<String, dynamic> json) {
  Model(value1: json['key1'], value2: json['key2'], value3: json['key3'], value4: json['key4'],);
 }

 Map<String, dynamic> toJson() => {
    'key1': value1,
    'key2': value2,
    'key3': value3,
    'key4': value4
  };
}

通过HTTP获取数据后,我将其解析为给定的对象,如下所示:     http.Response = http.get(urlHere);     最终的decodedJson = jsonDecode(response.body);     结果= Foo.fromJson(decodedJson).modelsAsJson;

解析后,结果从modelsAsJson获得正确的长度,但是该列表中的每个model的value1..value4均为null s。我在做什么错了?

2 个答案:

答案 0 :(得分:2)

在您的情况下,Model.fromJson(Map<String, dynamic> json)是一个命名构造函数,因此应在方括号内进行初始化。取而代之的是,您只是在构造函数中创建一个新的Model,而对其不执行任何操作。这就是为什么模型中的字段保持未初始化的状态(默认为null)。

应该这样写:

Model.fromJson(Map<String, dynamic> json) {
  value1 = json['key1'];
  value2 = json['key2'];
  value3 = json['key3'];
  value4 = json['key4'];
}

或者您可以使用工厂构造函数:

factory Model.fromJson(Map<String, dynamic> json) => Model(
    value1: json['key1'],
    value2: json['key2'],
    value3: json['key3'],
    value4: json['key4'],
  );

答案 1 :(得分:0)

尝试用以下内容替换您的模型类

// To parse this JSON data, do
//
//     final model = modelFromJson(jsonString);

import 'dart:convert';

List<Model> modelFromJson(String str) => List<Model>.from(json.decode(str).map((x) => Model.fromJson(x)));

String modelToJson(List<Model> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Model {
    String key1;
    String key2;
    String key3;
    String key4;

    Model({
        this.key1,
        this.key2,
        this.key3,
        this.key4,
    });

    factory Model.fromJson(Map<String, dynamic> json) => Model(
        key1: json["key1"] == null ? null : json["key1"],
        key2: json["key2"] == null ? null : json["key2"],
        key3: json["key3"] == null ? null : json["key3"],
        key4: json["key4"] == null ? null : json["key4"],
    );

    Map<String, dynamic> toJson() => {
        "key1": key1 == null ? null : key1,
        "key2": key2 == null ? null : key2,
        "key3": key3 == null ? null : key3,
        "key4": key4 == null ? null : key4,
    };
}

并使用下面的代码进行解析

List<Model> modelList = modelFromJson('Your Json String);