【问题标题】:How to fetch complex Json objects in flutter?如何在颤动中获取复杂的 Json 对象?
【发布时间】:2020-11-28 00:13:12
【问题描述】:

这是我要获取“分期付款”数组值的 API 响应

 {
 "unit":
      { 
    .....
      },
 "receipt": 
 {
   .....
 },
"instalments": [
    {
        "payment_type": "5",
        "amount": "3",
        "bank_name": "ABU DHABI COMMERCIAL BANK",
        "paid_date": "2020-08-07 01:11:02",
        "status": "0",
    }
    {
        "payment_type": "5",
        "amount": "3",
        "bank_name": "ABU DHABI COMMERCIAL BANK",
        "paid_date": "2020-08-07 01:11:02",
        "status": "0",
    }
    ]
  }

我使用这个模式类从 API 中获取价值

class PaymentInstallment {
 String payment_type;
 String payment_amount;
 String payment_date;
 String status;

 PaymentInstallment(
     {this.payment_type, this.payment_amount, this.payment_date, this.status});

  factory PaymentInstallment.fromjson(Map<String, dynamic> json) {
    return PaymentInstallment(
    payment_type: json['payment_type'],
    payment_amount: json['amount'],
  payment_date: json['paid_date'],
  status: json['status'],
       );
     }
    }

这是我的列表并将服务器的响应添加到它

   List<PaymentInstallment> _list = [];


  final response = await http.get(
    url,
    headers: {"Accept": "application/json", "Authorization": token},
   );
   var response = jsonDecode(response.body);
    setState(() {
    for (Map temppayment in response) {
      _list.add(PaymentInstallment.fromjson(temppayment));
     }
     });

如何将“分期付款”数组中的所有数组值添加到列表中

【问题讨论】:

  • json 数组“分期付款”中的字段与您在 PaymentInstallmet 类中的字段明显不同
  • 里面有我只贴几张的值
  • response["installments"] 这有你的 API 的列表或所有数组就用这个

标签: android ios json flutter dart


【解决方案1】:

试试这个

var response = jsonDecode(response.body);
List installmentList = List.from(response["installment"]);
setState((){
   _list = installmentList.map((f) => PaymentInstallment.fromJson(f)).toList();
});

如果它没有循环,试试这个

List tempList = [];
installmentList.forEach((f) => tempList.add(f));
setState((){
  _list = tempList;
});

【讨论】:

  • 谢谢,但它只显示了如何循环它的第一个索引值?
  • 对不起@Marzook 我没明白你的问题
  • @Marzook 检查另一个选项。我已经更新了答案
猜你喜欢
  • 2020-02-29
  • 2020-08-14
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多