Как я могу получить все идентификаторы команд из файла JSON во флаттере? - PullRequest
0 голосов
/ 10 февраля 2020

Я новичок во флаттере и пытаюсь получить значения из файла JSON с флаттером. Я мог бы получить некоторые значения идентификатора устройства и имени устройства, но я действительно не знаю, как получить идентификатор в командах. Спасибо заранее за вашу помощь.

Вот мой JSON файл:

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

Вот мой основной код флаттера:

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

А вот мой класс устройства:

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

1 Ответ

1 голос
/ 10 февраля 2020

вы можете разыграть json с классом ниже и получить команды устройства с устройством [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;
  }
}
...