Not Able to Fetch JSON values to field in flutter

半城伤御伤魂 提交于 2021-02-11 12:39:45

问题


I am able to fetch the JSON data successfully, but not able to fetch the fields of JSON data and build a list in flutter.

This is the code I am using to fetch the field data

OrderModel.fromJson(Map<String, dynamic> json) {
    error = json['error'];
    if (json['content'] != null) {
      content = new List<OrderContent>();
      json['content'].forEach((v) {

        content.add(new OrderContent.fromJson(v));
      });
    }
  }

The json['content'] is Map<String, dynamic>. In .forEach((v) what should I write to get the data? I am new to this flutter and JSON learning, I think I am wrong at this point only

THE JSON DATA STRUCTURE ON WHICH I AM WORKING IS BELOW

{
    "error": "false",
    "content": {
        "16": [
            [
                {
                    "sod_pk": "31688",
                    "soh_fk": "23660",
                    "sqd_fk": "33294",

                    "order_header": {
                        "soh_pk": "23660",
                        "order_no": "16",
                    }
                }
            ],
            [
                {
                    "sod_pk": "31689",
                    "soh_fk": "23660",
                    "sqd_fk": "33293",

                    "order_header": {
                        "soh_pk": "23660",
                        "order_no": "16",
                    }
                }
            ]
        ],
       




 "18": [
            [
                {
                    "sod_pk": "31744",
                    "soh_fk": "23702",
                    "sqd_fk": "33354",
                    "order_header": {
                        "soh_pk": "23702",
                        "order_no": "18",
                    }
                }
            ],
            [
                {
                    "sod_pk": "31745",
                    "soh_fk": "23702",
                    "sqd_fk": "33356",

                    "order_header": {
                        "soh_pk": "23702",
                        "order_no": "18",
                    }
                }
            ],
           
        ]
    }
}

the above JSON data structure has the order no nested in every item details, which has to be fetched inside all order numbers, then the respective data of orders.


回答1:


You can copy paste run full code below
Step 1: You can parse with payloadFromJson, content field is Map<String, List<List<OrderContent>>>, please see full code below
Step 2: Display with FutureBuilder and ListView.separated

working demo

full code

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  Payload({
    this.error,
    this.content,
  });

  String error;
  Map<String, List<List<OrderContent>>> content;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        error: json["error"],
        content: Map.from(json["content"]).map((k, v) =>
            MapEntry<String, List<List<OrderContent>>>(
                k,
                List<List<OrderContent>>.from(v.map((x) =>
                    List<OrderContent>.from(
                        x.map((x) => OrderContent.fromJson(x))))))),
      );

  Map<String, dynamic> toJson() => {
        "error": error,
        "content": Map.from(content).map((k, v) => MapEntry<String, dynamic>(
            k,
            List<dynamic>.from(
                v.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))))),
      };
}

class OrderContent {
  OrderContent({
    this.sodPk,
    this.sohFk,
    this.sqdFk,
    this.orderHeader,
  });

  String sodPk;
  String sohFk;
  String sqdFk;
  OrderHeader orderHeader;

  factory OrderContent.fromJson(Map<String, dynamic> json) => OrderContent(
        sodPk: json["sod_pk"],
        sohFk: json["soh_fk"],
        sqdFk: json["sqd_fk"],
        orderHeader: OrderHeader.fromJson(json["order_header"]),
      );

  Map<String, dynamic> toJson() => {
        "sod_pk": sodPk,
        "soh_fk": sohFk,
        "sqd_fk": sqdFk,
        "order_header": orderHeader.toJson(),
      };
}

class OrderHeader {
  OrderHeader({
    this.sohPk,
    this.orderNo,
  });

  String sohPk;
  String orderNo;

  factory OrderHeader.fromJson(Map<String, dynamic> json) => OrderHeader(
        sohPk: json["soh_pk"],
        orderNo: json["order_no"],
      );

  Map<String, dynamic> toJson() => {
        "soh_pk": sohPk,
        "order_no": orderNo,
      };
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<Payload> _future;

  Future<Payload> getData() async {
    String jsonString = '''
    {
    "error": "false",
    "content": {
        "16": [
            [
                {
                    "sod_pk": "31688",
                    "soh_fk": "23660",
                    "sqd_fk": "33294",
                    "order_header": {
                        "soh_pk": "23660",
                        "order_no": "16"
                    }
                }
            ],
            [
                {
                    "sod_pk": "31689",
                    "soh_fk": "23660",
                    "sqd_fk": "33293",
                    "order_header": {
                        "soh_pk": "23660",
                        "order_no": "16"
                    }
                }
            ]
        ],
        "18": [
            [
                {
                    "sod_pk": "31744",
                    "soh_fk": "23702",
                    "sqd_fk": "33354",
                    "order_header": {
                        "soh_pk": "23702",
                        "order_no": "18"
                    }
                }
            ],
            [
                {
                    "sod_pk": "31745",
                    "soh_fk": "23702",
                    "sqd_fk": "33356",
                    "order_header": {
                        "soh_pk": "23702",
                        "order_no": "18"
                    }
                }
            ]
           
        ]
    }
}
    ''';

    http.Response response = http.Response(jsonString, 200);
    if (response.statusCode == 200) {
      return payloadFromJson(response.body);
    }
  }

  @override
  void initState() {
    _future = getData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<Payload> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.separated(
                        separatorBuilder: (BuildContext context, int index) {
                          return SizedBox(
                            height: 30,
                          );
                        },
                        itemCount: snapshot.data.content.keys.length,
                        itemBuilder: (context, index) {
                          String key =
                              snapshot.data.content.keys.elementAt(index);

                          return Column(
                            children: [
                              Text(key),
                              ListView.separated(
                                separatorBuilder:
                                    (BuildContext context, int index) {
                                  return SizedBox(
                                    height: 10,
                                  );
                                },
                                shrinkWrap: true,
                                itemCount: snapshot.data.content[key].length,
                                itemBuilder: (context, index) {
                                  return Column(
                                    children: [
                                      Text(snapshot
                                          .data.content[key][index][0].sodPk),
                                      Text(snapshot
                                          .data.content[key][index][0].sqdFk),
                                      Text(snapshot.data.content[key][index][0]
                                          .orderHeader.sohPk),
                                    ],
                                  );
                                },
                              )
                            ],
                          );
                        });
                  }
              }
            }));
  }
}



回答2:


Your json is not optimize so difficult to handle. First of all, you see your json['content'] is not a list so you can't use foreach to get data. It is a object (map) {...}. But flutter don't know exactly it is map of what so you have to cast it. Secondly, to get sod_pk for example you have through 2 list. It's unnecessary. Here is the code

  final content = (data['content'] as Map<String, dynamic>);
  final sod_pk = content['16'].first.first['sod_pk'];
  print(sod_pk);


来源:https://stackoverflow.com/questions/63555004/not-able-to-fetch-json-values-to-field-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!