0

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 field.

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

this my json file

  {
    "name": "Lionel Messi",
    "email": "[email protected]",
    "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": "[email protected]",
      "creationDate": "21/04/20",
      "visuals": [
        {
          "type": "color",
          "value": "red",

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

    }
  }



]

this is 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 field.

1

1 Answer 1

2

You can copy paste run full code below
You can see full code of related class below

code snippet

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

full code

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": "[email protected]",
    "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": "[email protected]",
      "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),
      ),
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.