Search code examples
jsonapifluttergetrequest

How can i get all the commands id from a JSON file in flutter?


i'm a beginner in flutter and i'm trying to get values from a JSON file with flutter. I could get some the values of the device id and devices name but i really don'y know how to get the id in commands. Thank you in advance for your help.

Here is my JSON file :

[
    {
        "id": "15622bf9-969c-4f54-bd80-265a8132c97a",
        "name": "Random-Integer-Generator01",
        "adminState": "UNLOCKED",
        "operatingState": "ENABLED",
        "lastConnected": 0,
        "lastReported": 0,
        "labels": [
            "device-random-example"
        ],
        "location": null,
        "commands": [
            {
                "created": 1572962679310,
                "modified": 1572962679310,
                "id": "f07b4a42-4358-4394-bc71-76f292f8359f",
                "name": "GenerateRandomValue_Int8",
                "get": {
                    "path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int8",
                    "responses": [
                        {
                            "code": "503",
                            "description": "service unavailable"
                        }
                    ],
                    "url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/f07b4a42-4358-4394-bc71-76f292f8359f"
                },
                "put": {
                    "path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int8",
                    "parameterNames": [
                        "Min_Int8",
                        "Max_Int8"
                    ],
                    "url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/f07b4a42-4358-4394-bc71-76f292f8359f"
                }
            },
            {
                "created": 1572962679336,
                "modified": 1572962679336,
                "id": "86eafeb6-f359-40e7-b6c1-d35e9e9eb625",
                "name": "GenerateRandomValue_Int16",
                "get": {
                    "path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int16",
                    "responses": [
                        {
                            "code": "503",
                            "description": "service unavailable"
                        }
                    ],
                    "url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/86eafeb6-f359-40e7-b6c1-d35e9e9eb625"
                },
                "put": {
                    "path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int16",
                    "parameterNames": [
                        "Min_Int16",
                        "Max_Int16"
                    ],
                    "url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/86eafeb6-f359-40e7-b6c1-d35e9e9eb625"
                }
            },
            {
                "created": 1572962679337,
                "modified": 1572962679337,
                "id": "bb492384-8c72-4ab6-9a84-24a3be0b934e",
                "name": "GenerateRandomValue_Int32",
                "get": {
                    "path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int32",
                    "responses": [
                        {
                            "code": "503",
                            "description": "service unavailable"
                        }
                    ],
                    "url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/bb492384-8c72-4ab6-9a84-24a3be0b934e"
                },
                "put": {
                    "path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int32",
                    "parameterNames": [
                        "Min_Int32",
                        "Max_Int32"
                    ],
                    "url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/bb492384-8c72-4ab6-9a84-24a3be0b934e"
                }
            }
        ]
    },
    {
        "id": "97dcd3b2-f4f1-4a1a-9520-2ff62c697945",
        "name": "Random-Boolean-Device",
        "adminState": "UNLOCKED",
        "operatingState": "ENABLED",
        "lastConnected": 0,
        "lastReported": 0,
        "labels": [
            "device-virtual-example"
        ],
        "location": null,
        "commands": [
            {
                "created": 1572962679576,
                "modified": 1572962679576,
                "id": "1bc520ef-a9a4-43c7-8098-dcc5faea9ea1",
                "name": "RandomValue_Bool",
                "get": {
                    "path": "/api/v1/device/{deviceId}/RandomValue_Bool",
                    "responses": [
                        {
                            "code": "503",
                            "description": "service unavailable"
                        }
                    ],
                    "url": "http://edgex-core-command:48082/api/v1/device/97dcd3b2-f4f1-4a1a-9520-2ff62c697945/command/1bc520ef-a9a4-43c7-8098-dcc5faea9ea1"
                },
                "put": {
                    "path": "/api/v1/device/{deviceId}/RandomValue_Bool",
                    "parameterNames": [
                        "RandomValue_Bool",
                        "EnableRandomization_Bool"
                    ],
                    "url": "http://edgex-core-command:48082/api/v1/device/97dcd3b2-f4f1-4a1a-9520-2ff62c697945/command/1bc520ef-a9a4-43c7-8098-dcc5faea9ea1"
                }
            }
        ]
    },
]

Here is my main flutter code :

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

import 'GET.dart';
import 'Device.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  build(context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'My Http App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyListScreen(),
    );
  }
}

class MyListScreen extends StatefulWidget {
  @override
  createState() => _MyListScreenState();
}

class _MyListScreenState extends State {
  var device = new List<Device>();

  _getDevice() {
    GET.getDevice().then((response) {
      setState(() {
        Iterable list = json.decode(response.body);
        device = list.map((model) => Device.fromJson(model)).toList();
      });
    });
  }

  initState() {
    super.initState();
    _getDevice();
  }

  dispose() {
    super.dispose();
  }

  @override
  build(context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Device List"),
        ),
        body: ListView.builder(
          itemCount: device.length,
          itemBuilder: (context, index) {
            return ListTile(title: Text("Num $index "+device[index].id));
          },
        ));
  }
}

And here is my Device class :

class Device {
  //String 
  String id;
  String name;
  //String commands;

  Device(String id, String name) {
    this.id = id;
    this.name = name;
    //this.commands = commands; 
    //this.email = email;
  }

  Device.fromJson(Map json)
      : id = json['id'],
        name = json['name'];
        // commands = json['commands'];
        //['commands'][0]['name'], // marche

        //email = json['email'];

  Map toJson() {
    return {'id': id, 'name': name};
  }
}

Solution

  • you can cast json with below class and get commands of device with device[index].commands

    class Device {
      String id;
      String name;
      String adminState;
      String operatingState;
      int lastConnected;
      int lastReported;
      List<String> labels;
      Null location;
      List<Commands> commands;
    
      Device(
          {this.id,
          this.name,
          this.adminState,
          this.operatingState,
          this.lastConnected,
          this.lastReported,
          this.labels,
          this.location,
          this.commands});
    
      Device.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        name = json['name'];
        adminState = json['adminState'];
        operatingState = json['operatingState'];
        lastConnected = json['lastConnected'];
        lastReported = json['lastReported'];
        labels = json['labels'].cast<String>();
        location = json['location'];
        if (json['commands'] != null) {
          commands = new List<Commands>();
          json['commands'].forEach((v) {
            commands.add(new Commands.fromJson(v));
          });
        }
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['name'] = this.name;
        data['adminState'] = this.adminState;
        data['operatingState'] = this.operatingState;
        data['lastConnected'] = this.lastConnected;
        data['lastReported'] = this.lastReported;
        data['labels'] = this.labels;
        data['location'] = this.location;
        if (this.commands != null) {
          data['commands'] = this.commands.map((v) => v.toJson()).toList();
        }
        return data;
      }
    }
    
    class Commands {
      int created;
      int modified;
      String id;
      String name;
      Get get;
      Put put;
    
      Commands(
          {this.created, this.modified, this.id, this.name, this.get, this.put});
    
      Commands.fromJson(Map<String, dynamic> json) {
        created = json['created'];
        modified = json['modified'];
        id = json['id'];
        name = json['name'];
        get = json['get'] != null ? new Get.fromJson(json['get']) : null;
        put = json['put'] != null ? new Put.fromJson(json['put']) : null;
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['created'] = this.created;
        data['modified'] = this.modified;
        data['id'] = this.id;
        data['name'] = this.name;
        if (this.get != null) {
          data['get'] = this.get.toJson();
        }
        if (this.put != null) {
          data['put'] = this.put.toJson();
        }
        return data;
      }
    }
    
    class Get {
      String path;
      List<Responses> responses;
      String url;
    
      Get({this.path, this.responses, this.url});
    
      Get.fromJson(Map<String, dynamic> json) {
        path = json['path'];
        if (json['responses'] != null) {
          responses = new List<Responses>();
          json['responses'].forEach((v) {
            responses.add(new Responses.fromJson(v));
          });
        }
        url = json['url'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['path'] = this.path;
        if (this.responses != null) {
          data['responses'] = this.responses.map((v) => v.toJson()).toList();
        }
        data['url'] = this.url;
        return data;
      }
    }
    
    class Responses {
      String code;
      String description;
    
      Responses({this.code, this.description});
    
      Responses.fromJson(Map<String, dynamic> json) {
        code = json['code'];
        description = json['description'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['code'] = this.code;
        data['description'] = this.description;
        return data;
      }
    }
    
    class Put {
      String path;
      List<String> parameterNames;
      String url;
    
      Put({this.path, this.parameterNames, this.url});
    
      Put.fromJson(Map<String, dynamic> json) {
        path = json['path'];
        parameterNames = json['parameterNames'].cast<String>();
        url = json['url'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['path'] = this.path;
        data['parameterNames'] = this.parameterNames;
        data['url'] = this.url;
        return data;
      }
    }