当响应是对象数组时,如何在抖动中解析JSON

时间:2020-06-12 06:38:07

标签: json flutter dart

我收到以下类型的API响应

[
    {"name":"lakshay","id":"1217","type":"Staff","temperature":56.6,"date":"12-06-2020"},
    {"name":"lakshay","id":"1217","type":"Staff","temperature":56.6,"date":"12-06-2020"},
     .....
]

我需要将整个内容解析为对象列表,以便可以执行类似的操作

// conceptual //
array.map((obj)=>{
  // computation //
})

我从here那里获得了帮助,但没有说明如何解析外部数组。

感谢您的时间。

4 个答案:

答案 0 :(得分:2)

您可以使用下面的链接在线生成期望的响应类,并在您的项目中创建和保存类: https://javiercbk.github.io/json_to_dart/

有关更多详细信息,请参见此图像:

enter image description here

  class ApiRepositary {
      Dio dio;

      ApiRepositary() {
        if (dio == null) {
          BaseOptions options = new BaseOptions(
              baseUrl: "your base url",
              receiveDataWhenStatusError: true,
              connectTimeout: 60*1000, // 60 seconds
             receiveTimeout: 60*1000 // 60 seconds
         );

          dio = new Dio(options);
        }
      }


 Future<List<UserResponse>> getUserDetails() async {
    try {
      Response res = await dio.get("/lookup/pollquestion/add your url here");
      if (res.data.toString().isEmpty) {
        throw Exception();
      } else {
        final List rawData = jsonDecode(jsonEncode(res.data));
        List<UserResponse> response =
            rawData.map((f) => UserResponse.fromJson(f)).toList();
        return response;
      }
    } on DioError catch (dioError) {
      throw Exception(dioError);
   }
  }

}

要致电您班上的服务:

 ApiRepositary().getUserDetails().then((response){
          debugPrint("Login Success $response");
          //manage your response here, here you will get arralist as a response 

        },
          onError: (exception){
              //Handle exception message
            if(exception.message != null ){

              debugPrint(exception.message);

            }
         },
        );

答案 1 :(得分:1)

请使用此响应类

class YourResponse {
  String name;
  String id;
  String type;
  double temperature;
  String date;

  YourResponse({this.name, this.id, this.type, this.temperature, this.date});

  YourResponse.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    id = json['id'];
    type = json['type'];
    temperature = json['temperature'];
    date = json['date'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['id'] = this.id;
    data['type'] = this.type;
    data['temperature'] = this.temperature;
    data['date'] = this.date;
    return data;
  }
}

答案 2 :(得分:1)

您可以在下面复制粘贴运行完整代码
步骤1:使用List<Payload> payloadList = payloadFromJson(jsonString);进行解析,您可以看到完整的代码以获取详细信息Payload类定义
第2步:进行这样的循环

payloadList.forEach((element) {
      print(element.name);
      print(element.id);
    });

输出

I/flutter (17660): lakshay
I/flutter (17660): 1217
I/flutter (17660): lakshay
I/flutter (17660): 1217

完整代码

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

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

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

class Payload {
  Payload({
    this.name,
    this.id,
    this.type,
    this.temperature,
    this.date,
  });

  String name;
  String id;
  String type;
  double temperature;
  String date;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        name: json["name"],
        id: json["id"],
        type: json["type"],
        temperature: json["temperature"].toDouble(),
        date: json["date"],
      );

  Map<String, dynamic> toJson() => {
        "name": name,
        "id": id,
        "type": type,
        "temperature": temperature,
        "date": date,
      };
}

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> {
  int _counter = 0;
  String jsonString = '''
  [
    {"name":"lakshay","id":"1217","type":"Staff","temperature":56.6,"date":"12-06-2020"},
    {"name":"lakshay","id":"1217","type":"Staff","temperature":56.6,"date":"12-06-2020"}

]
''';

  void _incrementCounter() {
    List<Payload> payloadList = payloadFromJson(jsonString);
    payloadList.forEach((element) {
      print(element.name);
      print(element.id);
    });

    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

答案 3 :(得分:0)

假设

String  jsonResponse = '''[
    {"name":"lakshay","id":"1217","type":"Staff","temperature":56.6,"date":"12-06-2020"},
    {"name":"lakshay","id":"1217","type":"Staff","temperature":56.6,"date":"12-06-2020"}
]''';

您可以执行以下操作: 步骤1)导入“ dart:convert”包。 第2步)添加以下行:

List<dynamic> responses  = jsonDecode(jsonResponse);
  responses.forEach((obj){
      print(obj['name']);
  });

请记住上面的代码是一种快速而肮脏的方法,可以使事情正常进行。您可能会失去静态类型检查的许多好处。它始终建议使用chunhunghan建议的类。