Flutter和Distance Matrix API解析json [英] Flutter and Distance Matrix API parsing json

查看:85
本文介绍了Flutter和Distance Matrix API解析json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建一个flutter应用程序,该应用程序要在其中计算一些对象之间的距离,并正在使用Google Distance Matrix API进行计算。我在使用Dart解析json时遇到问题。我最终想要的只是与json结果的距离列表,以便我可以对其进行索引并将其应用于我应用程序中的数据。

I am currently building a flutter app where I want to calculate the distance between some objects and am using the Google Distance Matrix API to do so. I am having trouble parsing the json using Dart. All I want ultimately is a list of the distances from the json results so that I can index them and apply them to the data in my app.

json结果看起来像

The json results look like this:

{
   "destination_addresses" : [
      "destination address",
      "destination address"
   ],
   "origin_addresses" : [ "Origin addresses here" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "4.3 mi",
                  "value" : 6998
               },
               "duration" : {
                  "text" : "14 mins",
                  "value" : 848
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "6.7 mi",
                  "value" : 10728
               },
               "duration" : {
                  "text" : "22 mins",
                  "value" : 1327
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

我最终希望得到一个列表(以飞镖表示),该列表只是elements数组内距离文本值的列表,但是我很难让它返回。我尝试创建一个类并将json结果映射到此,但未成功,因为我不太擅长解析json,因此将不胜感激地收到有关如何以该列表结尾的任何建议!

I ultimately would like to end up with a list (in dart) that is just a list of the distance "text" values within the elements array but I am having trouble getting this to return. I have tried creating a class and mapping the json results to this but unsuccesfully as I am not very good at parsing json so any advice on how to end up with this list would be gratefully received!

我已经尝试过这段代码来解析json了,但是我真的很努力使其工作然后再应用它:

I have tried this code to parse the json but am really struggling to make it work and then apply it:

class Topleveladd {
  final String elements;

  Topleveladd({this.elements});

  factory Topleveladd.fromJson(Map<String, dynamic> parsedJson) {
    return Topleveladd(elements: parsedJson['rows']);
  }
}

class Elements {
  List<Distance> distanceslist;

  Elements({this.distanceslist});

  factory Elements.fromJson(Map<String, dynamic> parsedJson) {
    var list = parsedJson['elements'] as List;
    print(list.runtimeType); //returns List<dynamic>
    List<Distance> distancesList =
        list.map((i) => Distance.fromJson(i)).toList();
    return Elements(distanceslist: distancesList);
  }
}

class Distance {
  String text;
  Distance({this.text});

  factory Distance.fromJson(Map<String, dynamic> parsedJson) {
    return new Distance(
      text: parsedJson['distance'],
    );
  }
}


推荐答案

好这与我一起使用来访问您作为资产提供的JSON,因此您可能必须更改 loadData 方法以适合您的需求。

Okay this is it working with me accessing the JSON you've given as an asset so you'll probably have to change the loadData method for it to fit your needs.

DistanceMatrix类:

DistanceMatrix class:

import 'dart:convert';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

class DistanceMatrix {
  final List<String> destinations;
  final List<String> origins;
  final List<Element> elements;
  final String status;

  DistanceMatrix({this.destinations, this.origins, this.elements, this.status});

  factory DistanceMatrix.fromJson(Map<String, dynamic> json) {
    var destinationsJson = json['destination_addresses'];
    var originsJson = json['origin_addresses'];
    var rowsJson = json['rows'][0]['elements'] as List;

    return DistanceMatrix(
        destinations: destinationsJson.cast<String>(),
        origins: originsJson.cast<String>(),
        elements: rowsJson.map((i) => new Element.fromJson(i)).toList(),
        status: json['status']);
  }

  static Future<DistanceMatrix> loadData() async {
    DistanceMatrix distanceMatrix;
    try{
          String jsonData = await rootBundle.loadString('assets/data.json');
    distanceMatrix = new DistanceMatrix.fromJson(json.decode(jsonData));
    } catch (e){
      print(e);
    }
    return distanceMatrix;
  }
}

class Element {
  final Distance distance;
  final Duration duration;
  final String status;

  Element({this.distance, this.duration, this.status});

  factory Element.fromJson(Map<String, dynamic> json) {
    return Element(
        distance: new Distance.fromJson(json['distance']),
        duration: new Duration.fromJson(json['duration']),
        status: json['status']);
  }
}

class Distance {
  final String text;
  final int value;

  Distance({this.text, this.value});

  factory Distance.fromJson(Map<String, dynamic> json) {
    return new Distance(text: json['text'], value: json['value']);
  }
}

class Duration {
  final String text;
  final int value;

  Duration({this.text, this.value});

  factory Duration.fromJson(Map<String, dynamic> json) {
    return new Duration(text: json['text'], value: json['value']);
  }
}

使用的Main.dart ListView.builder 将距离文本和值显示为 ListTile

Main.dart which uses ListView.builder to display the distances text and values as a ListTile:

import 'package:flutter/material.dart';
import 'package:hello_world/distance_matrix.dart';

void main() async {
  runApp(new MyApp(
    distanceMatrix: await DistanceMatrix.loadData(),
  ));
}

class MyApp extends StatefulWidget {
  final DistanceMatrix distanceMatrix;

  @override
  _MyAppState createState() => new _MyAppState();

  MyApp({this.distanceMatrix});
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text("Home"),
            ),
            body: Material(
                child: ListView.builder(
                itemCount: widget.distanceMatrix.elements.length,
                itemBuilder: (context, index){
                  return ListTile(
                    title: Text(widget.distanceMatrix.elements[index].distance.text),
                    subtitle: Text(widget.distanceMatrix.elements[index].distance.value.toString()),
                  );
                },
              )
            )));
  }
}

显示您应该得到的图像:

Image to show what you should get:

这篇关于Flutter和Distance Matrix API解析json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆