如何通过模型(父类和子类)访问API响应数据?

时间:2019-06-17 22:26:43

标签: flutter dart

我正在尝试访问API响应数据,但是当我尝试使用模型访问数据时显示为空。如何使用模型访问所有响应数据?

这是我到目前为止所做的:

if (response.statusCode == 200) {
  var res = json.decode(response.body);
  print("Ress...$res"); //PRINTS THE MAPPED DATA
  Gate gate = new Gate.fromJson(res);
  print(gate.a.b); // PRINTS NULL

上面的代码返回null。如何访问数据?我可以通过父级访问所有(父级和子级数据)吗?

已编辑

@JsonSerializable()
class Gate {
  @JsonKey(name: "A")
  A a;

  Gate(this.a);
  factory Gate.fromJson(Map<String, dynamic> json) =>
  _$GateFromJson(json);
}

A类

@JsonSerializable()
class A {
  @JsonKey(name: "B")
  B b;
  @JsonKey(name: "C")
  C c;

  A(this.b,this.c);

  factory A.fromJson(Map<String, dynamic> json) => _$AFromJson(json);
}

B类

@JsonSerializable()
class B {
   @JsonKey(name: "D")
   List<D> listOfD;
   B(this.listOfD);

   factory B.fromJson(Map<String, dynamic> json) => _$BFromJson(json);
}

C类

  @JsonSerializable()
  class C {
   @JsonKey(name: "productID")
   double productId;
   C(this.productId);

   factory C.fromJson(Map<String, dynamic> json) => _$CFromJson(json);
 }

D类

@JsonSerializable()
class D {
   @JsonKey(name: "Name")
   String name;
   D(this.name);

  factory D.fromJson(Map<String, dynamic> json) => _$DFromJson(json);

}

这是json数据

{
"A": {
    "B": [
        {
            "Name": "name1"
        },
        {
            "Name": "name2"
        },
        {
            "Name": "name3"
        }
    ],
    "C": {
        "productID": 111.2
    }
}}

我已经根据上述模型自动创建了x.g.dart。它仍然返回null

1 个答案:

答案 0 :(得分:0)

您的数据模型声明不正确(不是根据您的数据)。

请检查示例代码。它按预期工作。

import 'dart:convert';

import 'json_objects.dart';

main(List<String> args) {
  var res = json.decode(body) as Map<String, dynamic>;
  print("Ress...$res"); //PRINTS THE MAPPED DATA
  var data = Data.fromJson(res);
  print(data.a.b); //PRINTS NULL
}

var body = '''
{
"A": {
    "B": [
        {
            "Name": "name1"
        },
        {
            "Name": "name2"
        },
        {
            "Name": "name3"
        }
    ],
    "C": {
        "productID": 111.2
    }
}}''';
Ress...{A: {B: [{Name: name1}, {Name: name2}, {Name: name3}], C: {productID: 111.2}}}
[Instance of 'B', Instance of 'B', Instance of 'B']

正确的数据模型:

class A {
  final List<B> b;
  final C c;

  A({this.b, this.c});

  factory A.fromJson(Map<String, dynamic> json) {
    return A(
      b: _toObjectList(json['B'], (e) => B.fromJson(e)),
      c: _toObject(json['C'], (e) => C.fromJson(e)),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'B': _fromList(b, (e) => e.toJson()),
      'C': c?.toJson(),
    };
  }
}

class B {
  final String name;

  B({this.name});

  factory B.fromJson(Map<String, dynamic> json) {
    return B(
      name: json['Name'] as String,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'Name': name,
    };
  }
}

class C {
  final double productID;

  C({this.productID});

  factory C.fromJson(Map<String, dynamic> json) {
    return C(
      productID: _toDouble(json['productID']),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'productID': productID,
    };
  }
}

class Data {
  final A a;

  Data({this.a});

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
      a: _toObject(json['A'], (e) => A.fromJson(e)),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'A': a?.toJson(),
    };
  }
}

List _fromList(data, Function(dynamic) toJson) {
  if (data == null) {
    return null;
  }
  var result = [];
  for (var element in data) {
    var value;
    if (element != null) {
      value = toJson(element);
    }
    result.add(value);
  }
  return result;
}

double _toDouble(data) {
  if (data == null) {
    return null;
  }
  if (data is int) {
    return data.toDouble();
  }
  return data as double;
}

T _toObject<T>(data, T Function(Map<String, dynamic>) fromJson) {
  if (data == null) {
    return null;
  }
  return fromJson(data as Map<String, dynamic>);
}

List<T> _toObjectList<T>(data, T Function(Map<String, dynamic>) fromJson) {
  if (data == null) {
    return null;
  }
  var result = <T>[];
  for (var element in data) {
    T value;
    if (element != null) {
      value = fromJson(element as Map<String, dynamic>);
    }
    result.add(value);
  }
  return result;
}

/*
Data:
  A: A

A:
  B: List<B>
  C: C
B:
  Name: String

C:
  productID: double
*/

P.S。

应以以下方式声明模型:

Data:
  A: A

A:
  B: List<B>
  C: C

B:
  Name: String

C:
  productID: double