0

I am getting an API response of the following type

[
    {"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"},
     .....
]

I need to parse the whole thing as List of objects, so that I can do something like

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

I took help from here but it doesn't tell how to parse the outer array.

thanks for your time.

Lakshay Dutta
  • 455
  • 5
  • 20

4 Answers4

4

You can generate expected response class online using below link and create and save class in your project : https://javiercbk.github.io/json_to_dart/

For more details see this image :

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);
   }
  }

}

To call service in your class :

 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);

            }
         },
        );
Sathish Gadde
  • 1,453
  • 16
  • 28
1

Please use this response class

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;
  }
}
1

You can copy paste run full code below
Step 1: parse with List<Payload> payloadList = payloadFromJson(jsonString); , you can see full code for detail Payload class definition
Step 2: For loop like this

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

output

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

full code

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),
      ),
    );
  }
}
chunhunghan
  • 51,087
  • 5
  • 102
  • 120
0

Assuming

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"}
]''';

You could do something as below: Step 1) import 'dart:convert' package. Step 2 ) Add following lines:

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

Remember the above code is a quick & dirty way get things working.you may lose many benefits of static type checking.It always recommended that use classes created as suggested by chunhunghan.

Sanath.usk
  • 84
  • 5