десериализовать геометрический многоугольник из mongodb - PullRequest
0 голосов
/ 16 апреля 2020

Я новичок, чтобы трепетать и пытался десериализовать гео json из моего API.

полученный гео json выглядит примерно так:

[
    {
        "_id": {
            "$oid": "5e95d60049ebb0e6b45a34e6"
        },
        "type": "Feature",
        "geometry": {
            "type": "Polygon",
            "coordinates": [
                [
                    [
                        14.810392700000136,
                        50.8584471640001
                    ],
                    [
                        14.867856893000067,
                        50.8643899540001
                    ]
                ]
            ]
        },
        "properties": {
            "ADMIN": "Test",
            "ISO_A3": "TST",
            "ISO_A2": "TS"
        }
    }
]

я пытался использовать страницу JSON to Dart (https://javiercbk.github.io/json_to_dart/) для извлечения модели, которую я могу использовать во флаттере ... но он говорит, что сгенерированный код является недопустимой причиной 3 списков внутри элемента координат

проблема в сгенерированном коде здесь:

    Geometry.fromJson(Map<String, dynamic> json) {
        type = json['type'];
        if (json['coordinates'] != null) {
            coordinates = new List<List>();
            json['coordinates'].forEach((v) { coordinates.add(new List.fromJson(v)); });
        }
    }

кто-нибудь может мне помочь решить проблему 3 списков в списке?

1 Ответ

1 голос
/ 16 апреля 2020

Вы можете скопировать вставленный полный код ниже
Вы можете увидеть Geometry определение класса в полном коде
фрагмент кода

class Geometry {
  String type;
  List<List<List<double>>> coordinates;
...  
factory Geometry.fromJson(Map<String, dynamic> json) => Geometry(
        type: json["type"],
        coordinates: List<List<List<double>>>.from(json["coordinates"].map(
            (x) => List<List<double>>.from(
                x.map((x) => List<double>.from(x.map((x) => x.toDouble())))))),
      );


print(payloadList[0].id.oid);
print(payloadList[0].geometry.coordinates[0][0][0]);
print(payloadList[0].geometry.coordinates[0][0][1]);
print(payloadList[0].geometry.coordinates[0][1][0]);
print(payloadList[0].geometry.coordinates[0][1][1]);

выход

I/flutter (25078): 5e95d60049ebb0e6b45a34e6
I/flutter (25078): 14.810392700000136
I/flutter (25078): 50.8584471640001
I/flutter (25078): 14.867856893000067
I/flutter (25078): 50.8643899540001

полный код

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 {
  Id id;
  String type;
  Geometry geometry;
  Properties properties;

  Payload({
    this.id,
    this.type,
    this.geometry,
    this.properties,
  });

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        id: Id.fromJson(json["_id"]),
        type: json["type"],
        geometry: Geometry.fromJson(json["geometry"]),
        properties: Properties.fromJson(json["properties"]),
      );

  Map<String, dynamic> toJson() => {
        "_id": id.toJson(),
        "type": type,
        "geometry": geometry.toJson(),
        "properties": properties.toJson(),
      };
}

class Geometry {
  String type;
  List<List<List<double>>> coordinates;

  Geometry({
    this.type,
    this.coordinates,
  });

  factory Geometry.fromJson(Map<String, dynamic> json) => Geometry(
        type: json["type"],
        coordinates: List<List<List<double>>>.from(json["coordinates"].map(
            (x) => List<List<double>>.from(
                x.map((x) => List<double>.from(x.map((x) => x.toDouble())))))),
      );

  Map<String, dynamic> toJson() => {
        "type": type,
        "coordinates": List<dynamic>.from(coordinates.map((x) =>
            List<dynamic>.from(
                x.map((x) => List<dynamic>.from(x.map((x) => x)))))),
      };
}

class Id {
  String oid;

  Id({
    this.oid,
  });

  factory Id.fromJson(Map<String, dynamic> json) => Id(
        oid: json["\u0024oid"],
      );

  Map<String, dynamic> toJson() => {
        "\u0024oid": oid,
      };
}

class Properties {
  String admin;
  String isoA3;
  String isoA2;

  Properties({
    this.admin,
    this.isoA3,
    this.isoA2,
  });

  factory Properties.fromJson(Map<String, dynamic> json) => Properties(
        admin: json["ADMIN"],
        isoA3: json["ISO_A3"],
        isoA2: json["ISO_A2"],
      );

  Map<String, dynamic> toJson() => {
        "ADMIN": admin,
        "ISO_A3": isoA3,
        "ISO_A2": isoA2,
      };
}

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;

  void _incrementCounter() {
    String jsonString = '''
    [
    {
        "_id": {
            "\$oid": "5e95d60049ebb0e6b45a34e6"
        },
        "type": "Feature",
        "geometry": {
            "type": "Polygon",
            "coordinates": [
                [
                    [
                        14.810392700000136,
                        50.8584471640001
                    ],
                    [
                        14.867856893000067,
                        50.8643899540001
                    ]
                ]
            ]
        },
        "properties": {
            "ADMIN": "Test",
            "ISO_A3": "TST",
            "ISO_A2": "TS"
        }
    }
]
    ''';
    List<Payload> payloadList = payloadFromJson(jsonString);

    print(payloadList[0].id.oid);
    print(payloadList[0].geometry.coordinates[0][0][0]);
    print(payloadList[0].geometry.coordinates[0][0][1]);
    print(payloadList[0].geometry.coordinates[0][1][0]);
    print(payloadList[0].geometry.coordinates[0][1][1]);
    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),
      ),
    );
  }
}
...