繁体   English   中英

在嵌套的 object flutter 中解析复杂的 json

[英]parsing complex json in nested object flutter

parsing complex json in nested object flutter I'm trying to pull the data from a list that is inside an object that is inside an object Trying to pull the type and value Suppose I want to access the visuals contains some fields and an array of objects场地。

     "visuals": [{"type": "color", "value": "red"},]

这是我的 json 文件

  {
    "name": "Lionel Messi",
    "email": "LionelMessi@gmail.com",
    "age": "23",
    "photo": "https://img.bleacherreport.net/img/images/photos/003/738/191/hi-res-bd496f7bef33e47363703d3cce58c50e_crop_north.jpg?h=533&w=800&q=70&crop_x=center&crop_y=top",
    "url": "http://www.john-wesley.com",
    "trainingPlan": {
      "id": "1",
      "creator": "LionelMessi@gmail.com",
      "creationDate": "21/04/20",
      "visuals": [
        {
          "type": "color",
          "value": "red",

        }
      ],
      "transition": {"length": "2", "delay": "1"},
      "duration": {"type": "Countdown", "time": "20"}

    }
  }



]

这是 flutter

import 'dart:convert';

class Record {
  String name;
  String email;
  String age;
  String photo;
  String url;
  final trainingPlan;

  Record({
    this.name,
    this.email,
    this.age,
    this.photo,
    this.url,
    this.trainingPlan,
  });

  factory Record.fromJson(Map<String, dynamic> json) {
    return new Record(
      name: json['name'],
      email: json['email'],
      age: json['age'],
      photo: json['photo'],
      url: json['url'],
      trainingPlan: TrainingPlan.fromJson(json['trainingPlan']),
    );
  }
}

class TrainingPlan {
  final String id;
  final String creator;
  final String creationDate;
  final transition;
  final duration;
  final List<Visuals> visuals;

  TrainingPlan(
      {this.id,
      this.creator,
      this.creationDate,
      this.transition,
      this.duration,
      this.visuals});

  TrainingPlan.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        creator = json['creator'],
        creationDate = json['creationDate'],
        transition = Transition.fromJson(json['transition']),
        duration = Duration.fromJson(json['duration']),
        visuals = parseVisuals(json);

  static List<Visuals> parseVisuals(visualsJson) {
    var list = visualsJson['visuals'] as List;
    List<Visuals> visualsList =
    list.map((data) => Visuals.fromJson(data)).toList();
    return visualsList;
  }
}

class Transition {
  final String length;
  final String delay;

  Transition({
    this.length,
    this.delay,
  });

  Transition.fromJson(Map<String, dynamic> json)
      : length = json['length'],
        delay = json['delay'];
}

class Duration {
  final String type;
  final String time;

  Duration({
    this.type,
    this.time, int seconds,
  });

  Duration.fromJson(Map<String, dynamic> json)
      : type = json['type'],
        time = json['time'];
}

class Visuals {
  final String type;
  final String value;

  Visuals({this.type, this.value});

  factory Visuals.fromJson(Map<String, dynamic> parsedJson) {
    return Visuals(
        type: parsedJson['type'],
        value: parsedJson['value'],
  }
}

parsing complex json in nested object flutter I'm trying to pull the data from a list that is inside an object that is inside an object Trying to pull the type and value Suppose I want to access the visuals contains some fields and an array of objects场地。

您可以在下面复制粘贴运行完整代码
您可以在下面看到相关 class 的完整代码

代码片段

Record recordFromJson(String str) => Record.fromJson(json.decode(str));
...
Record record = recordFromJson(jsonString);
print(
    '${record.trainingPlan.visuals[0].type} ${record.trainingPlan.visuals[0].value}');

output

I/flutter (30092): color red

完整代码

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

Record recordFromJson(String str) => Record.fromJson(json.decode(str));

String recordToJson(Record data) => json.encode(data.toJson());

class Record {
  String name;
  String email;
  String age;
  String photo;
  String url;
  TrainingPlan trainingPlan;

  Record({
    this.name,
    this.email,
    this.age,
    this.photo,
    this.url,
    this.trainingPlan,
  });

  factory Record.fromJson(Map<String, dynamic> json) => Record(
        name: json["name"],
        email: json["email"],
        age: json["age"],
        photo: json["photo"],
        url: json["url"],
        trainingPlan: TrainingPlan.fromJson(json["trainingPlan"]),
      );

  Map<String, dynamic> toJson() => {
        "name": name,
        "email": email,
        "age": age,
        "photo": photo,
        "url": url,
        "trainingPlan": trainingPlan.toJson(),
      };
}

class TrainingPlan {
  String id;
  String creator;
  String creationDate;
  List<Visual> visuals;
  Transition transition;
  Duration duration;

  TrainingPlan({
    this.id,
    this.creator,
    this.creationDate,
    this.visuals,
    this.transition,
    this.duration,
  });

  factory TrainingPlan.fromJson(Map<String, dynamic> json) => TrainingPlan(
        id: json["id"],
        creator: json["creator"],
        creationDate: json["creationDate"],
        visuals:
            List<Visual>.from(json["visuals"].map((x) => Visual.fromJson(x))),
        transition: Transition.fromJson(json["transition"]),
        duration: Duration.fromJson(json["duration"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "creator": creator,
        "creationDate": creationDate,
        "visuals": List<dynamic>.from(visuals.map((x) => x.toJson())),
        "transition": transition.toJson(),
        "duration": duration.toJson(),
      };
}

class Duration {
  String type;
  String time;

  Duration({
    this.type,
    this.time,
  });

  factory Duration.fromJson(Map<String, dynamic> json) => Duration(
        type: json["type"],
        time: json["time"],
      );

  Map<String, dynamic> toJson() => {
        "type": type,
        "time": time,
      };
}

class Transition {
  String length;
  String delay;

  Transition({
    this.length,
    this.delay,
  });

  factory Transition.fromJson(Map<String, dynamic> json) => Transition(
        length: json["length"],
        delay: json["delay"],
      );

  Map<String, dynamic> toJson() => {
        "length": length,
        "delay": delay,
      };
}

class Visual {
  String type;
  String value;

  Visual({
    this.type,
    this.value,
  });

  factory Visual.fromJson(Map<String, dynamic> json) => Visual(
        type: json["type"],
        value: json["value"],
      );

  Map<String, dynamic> toJson() => {
        "type": type,
        "value": value,
      };
}

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 = '''
    {
    "name": "Lionel Messi",
    "email": "LionelMessi@gmail.com",
    "age": "23",
    "photo": "https://img.bleacherreport.net/img/images/photos/003/738/191/hi-res-bd496f7bef33e47363703d3cce58c50e_crop_north.jpg?h=533&w=800&q=70&crop_x=center&crop_y=top",
    "url": "http://www.john-wesley.com",
    "trainingPlan": {
      "id": "1",
      "creator": "LionelMessi@gmail.com",
      "creationDate": "21/04/20",
      "visuals": [
        {
          "type": "color",
          "value": "red"
        }
      ],
      "transition": {"length": "2", "delay": "1"},
      "duration": {"type": "Countdown", "time": "20"}
    }
}
    ''';

    Record record = recordFromJson(jsonString);
    print(
        '${record.trainingPlan.visuals[0].type} ${record.trainingPlan.visuals[0].value}');

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM