如何使用POST Flutter解析嵌套的Json

时间:2019-05-19 13:56:22

标签: arrays json dart flutter

我想用flutter http解析嵌套的json。 我编写代码,但ListView.builder中没有显示数据。

我尝试使用格式嵌套的json,但与POST http不相关,因为我的API必须发送API密钥以获取响应值。

此Json嵌套结果。

{
    "status": 1,
    "status_message": "Success!",
    "result": [
        {
            "id": "1",
            "ticket": "377292",
            "departmentid": "1",
            "clientid": "1",
            "userid": "0",
            "adminid": "1",
            "assetid": "1",
            "projectid": "1",
            "email": "email@email.com",
            "subject": "Test",
            "status": "Answered",
            "priority": "Normal",
            "timestamp": "2019-04-02 16:06:32",
            "notes": "",
            "ccs": false,
            "timespent": "0"
        },
        {
            "id": "2",
            "ticket": "424327",
            "departmentid": "1",
            "clientid": "1",
            "userid": "1",
            "adminid": "1",
            "assetid": "1",
            "projectid": "0",
            "email": "email@email.com",
            "subject": "test Tiket",
            "status": "Open",
            "priority": "Normal",
            "timestamp": "2019-05-19 05:48:37",
            "notes": "",
            "ccs": false,
            "timespent": "0"
        }
    ]
}

这是我的Flutter代码,请为我的问题提供建议。

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:ticket_new/modal/ticketModel.dart';
import 'package:http/http.dart' as http;
class Report extends StatefulWidget {
  @override
  _ReportState createState() => _ReportState();
}

class _ReportState extends State<Report> {

  List<TicketModel> _list = [];
  var loading = false;
  Future<Null> _fetchData() async{
    setState(() {
      loading = true;
    });
    final response = await http.post("http://192.168.43.253/edc/api/index.php", body: {
      'key' : '5fpqRt23yU2kgJcl7fDo6ARIzsU5zIGAOIYtNPDBNokQcRViNfKnbaSiNow61lXG',
      'method' : 'get',
      'resource' : 'tickets',
    });
    if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        setState(() {
          for (Map i in data) {
          _list.add(TicketModel.fromJson(i));
          }
          loading = false;
        });
    } else {
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: Container(
        child: loading
        ? Center(child: CircularProgressIndicator())
        : ListView.builder(
          itemCount: _list.length,
          itemBuilder: (context, i){
            final x = _list[i];
            return Container(
              padding: EdgeInsets.all(10.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(x.result.email),

                  Text(x.result.subject),
                ],
              ),
              );
          },
        ),
      ),
    );
  }
}

这是我在Flutter代码中的Model Constructor。

class TicketModel{
  final int status;
  final String status_message;
  final ResultTicket result;

  TicketModel({this.status, this.status_message, this.result});
  factory TicketModel.fromJson(Map<String, dynamic> json) {
    return new TicketModel(
        status: json['status'],
        status_message: json['status_message'],
        result: ResultTicket.fromJson(json['result'],
        ));
  }
}

class ResultTicket{
  final int id;
  final int ticket;
  final int departmentid;
  final int clientid;
  final int userid;
  final int adminid;
  final int assetid;
  final int projectid;
  final String email;
  final String subject;
  final String status;
  final String priority;
  final String timestamp;
  final String notes;
  final String ccs;
  final int timespent;

  ResultTicket({this.id, this.ticket, this.departmentid, this.clientid, this.userid, this.adminid, this.assetid, this.projectid, this.email, this.subject, this.status, this.priority, this.timestamp, this.notes, this.ccs, this.timespent});

  factory ResultTicket.fromJson(Map<String, dynamic> json) {
    return new ResultTicket(
      id: json['id'],
      ticket: json['ticket'],
      departmentid: json['depatmentid'],
      clientid: json['clientid'],
      userid: json['userid'],
      adminid: json['adminid'],
      assetid: json['assetid'],
      projectid: json['projectid'],
      email: json['email'],
      subject: json['subject'],
      status: json['status'],
      priority: json['priority'],
      timestamp: json['timestamp'],
      notes: json['notes'],
      ccs: json['ccs'],
      timespent: json['timespent'],
    );
  }

}

1 个答案:

答案 0 :(得分:0)

首先,解析ResultTicket中的JSON值:

class ResultTicket {
  final int id;
  final int ticket;
  final int departmentid;
  final int clientid;
  final int userid;
  final int adminid;
  final int assetid;
  final int projectid;
  final String email;
  final String subject;
  final String status;
  final String priority;
  final String timestamp;
  final String notes;
  final bool ccs;
  final int timespent;

  ResultTicket({
    this.id,
    this.ticket,
    this.departmentid,
    this.clientid,
    this.userid,
    this.adminid,
    this.assetid,
    this.projectid,
    this.email,
    this.subject,
    this.status,
    this.priority,
    this.timestamp,
    this.notes,
    this.ccs,
    this.timespent,
  });

  factory ResultTicket.fromJson(Map<String, dynamic> json) {
    return new ResultTicket(
      id: parseToIntIfNotNull(json['id']),
      ticket: parseToIntIfNotNull(json['ticket']),
      departmentid: parseToIntIfNotNull(json['depatmentid']),
      clientid: parseToIntIfNotNull(json['clientid']),
      userid: parseToIntIfNotNull(json['userid']),
      adminid: parseToIntIfNotNull(json['adminid']),
      assetid: parseToIntIfNotNull(json['assetid']),
      projectid: parseToIntIfNotNull(json['projectid']),
      email: json['email'],
      subject: json['subject'],
      status: json['status'],
      priority: json['priority'],
      timestamp: json['timestamp'],
      notes: json['notes'],
      ccs: json['ccs'],
      timespent: parseToIntIfNotNull(json['timespent']),
    );
  }

  static int parseToIntIfNotNull(String string) {
    if (string == null) return null;
    else return int.parse(string);
  }
}

第二,您没有TicketModel的列表,而您有ResultTicket的列表,因此请更改您的TicketModel以提取并存储该ResultTicket列表:< / p>

class TicketModel {
  final int status;
  final String status_message;
  final List<ResultTicket> results;

  TicketModel({this.status, this.status_message, this.results});

  factory TicketModel.fromJson(Map<String, dynamic> json) {
    List<ResultTicket> results = (json['result'] as List)
        .map((resultTicketJson) => ResultTicket.fromJson(resultTicketJson))
        .toList();

    return TicketModel(
      status: json['status'],
      status_message: json['status_message'],
      results: results,
    );
  }
}

然后使您的小部件适应这些更改:

class Report extends StatefulWidget {
  @override
  _ReportState createState() => _ReportState();
}

class _ReportState extends State<Report> {
  TicketModel ticketModel;
  bool loading;

  Future<Null> _fetchData() async {
    setState(() => loading = true);

    final response = await http.post("http://192.168.43.253/edc/api/index.php", body: {
      'key' : '5fpqRt23yU2kgJcl7fDo6ARIzsU5zIGAOIYtNPDBNokQcRViNfKnbaSiNow61lXG',
      'method' : 'get',
      'resource' : 'tickets',
    });

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      final ticketModelFromJson = TicketModel.fromJson(data);

      setState(() {
        ticketModel = ticketModelFromJson;
        loading = false;
      });
    } else {
    }
  }

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: loading
            ? Center(child: CircularProgressIndicator())
            : ListView.builder(
                itemCount: ticketModel.results.length,
                itemBuilder: (context, i) {
                  final x = ticketModel.results[i];
                  return Container(
                    padding: EdgeInsets.all(10.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(x.email),
                        Text(x.subject),
                      ],
                    ),
                  );
                },
              ),
      ),
    );
  }
}