在嵌套对象波动中解析复杂的json 我正在尝试从对象内部的对象列表中提取数据 试图拉类型和价值 假设我要访问视觉效果 包含一些字段和一组对象字段。
"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"}
}
}
]
这很扑朔迷离
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'],
}
}
在嵌套对象波动中解析复杂的json 我正在尝试从对象内部的对象列表中提取数据 试图拉类型和价值 假设我要访问视觉效果 包含一些字段和一组对象字段。
答案 0 :(得分:1)
您可以在下面复制粘贴运行完整代码
您可以在下面查看相关类的完整代码
代码段
Record recordFromJson(String str) => Record.fromJson(json.decode(str));
...
Record record = recordFromJson(jsonString);
print(
'${record.trainingPlan.visuals[0].type} ${record.trainingPlan.visuals[0].value}');
输出
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),
),
);
}
}