返回文章页面如何在 Deserialize 找到 json in flutter 的物品清单

我正在使用 dart 包 json _ Series alizable 进行 json 序列化。查看 flutter 文档,它显示了如何反序列化单个对象,如下所示:

Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');


if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}

然而,我对 Dart 还不够熟悉,不知道如何对一个项目列表而不是单个实例执行相同的操作。

171200 次浏览

那么,您的服务将处理响应主体是一个映射,或者相应地处理映射列表。根据您的代码,您计算了1个项目。

如果响应主体是可迭代的,那么如果我正确理解了您的问题,那么您需要进行相应的解析和遍历。

例如:

Iterable l = json.decode(response.body);
List<Post> posts = List<Post>.from(l.map((model)=> Post.fromJson(model)));

其中的帖子是一个帖子列表。

编辑 : 我想在这里添加一个清晰的注释。这里的目的是解码返回的响应。下一步是将可迭代的 JSON 对象转换为对象的实例。这是通过在类中创建 from JSON 方法来完成的,以便正确地接受 JSON 并相应地实现它。下面是一个示例实现。

class Post {
// Other functions and properties relevant to the class
// ......
/// Json is a Map<dynamic,dynamic> if i recall correctly.
static fromJson(json): Post {
Post p = new Post()
p.name = ...
return p
}
}

这些天我有点抽象的达特,赞成一个更好的实用工具的任务需要完成。所以我的语法可能有点偏离,但这是伪代码。

这只是 JSON 解析的另一个例子,需要进一步说明。

假设我们想要解析 JSON 对象中的条目数组。

factory YoutubeResponse.fromJSON(Map<String, dynamic> YoutubeResponseJson)
{


// Below 2 line code is parsing JSON Array of items in our JSON Object (YouttubeResponse)




var list = YoutubeResponseJson['items'] as List;
List<Item> itemsList = list.map((i) => Item.fromJSON(i)).toList();


return new YoutubeResponse(
kind: YoutubeResponseJson['kind'],
etag: YoutubeResponseJson['etag'],
nextPageToken: YoutubeResponseJson['nextPageToken'],
regionCode: YoutubeResponseJson['regionCode'],
mPageInfo: pageInfo.fromJSON(YoutubeResponseJson['pageInfo']),


// Here we are returning parsed JSON Array.


items: itemsList);


}

首先,创建一个与 json 数据匹配的类,在我的例子中,我创建(生成)名为 Img的类:

import 'dart:convert';


Img imgFromJson(String str) => Img.fromJson(json.decode(str));
String imgToJson(Img data) => json.encode(data.toJson());


class Img {
String id;
String img;
dynamic decreption;


Img({
this.id,
this.img,
this.decreption,
});


factory Img.fromJson(Map<String, dynamic> json) => Img(
id: json["id"],
img: json["img"],
decreption: json["decreption"],
);


Map<String, dynamic> toJson() => {
"id": id,
"img": img,
"decreption": decreption,
};
}

您可以使用 App.quicktype.io在 dart 中生成您的 json 数据类。 然后把你的文章发送到你的服务器:

Future<List<Img>> _getimages() async {
var response = await http.get("http://192.168.115.2/flutter/get_images.php");
var rb = response.body;


// store json data into list
var list = json.decode(rb) as List;


// iterate over the list and map each object in list to Img by calling Img.fromJson
List<Img> imgs = list.map((i)=>Img.fromJson(i)).toList();


print(imgs.runtimeType); //returns List<Img>
print(imgs[0].runtimeType); //returns Img


return imgs;
}

更多信息见 在 Flutter 中解析复杂的 JSON

你也可以这样做

  List<dynamic> parsedListJson = jsonDecode("your json string");
List<Item> itemsList = List<Item>.from(parsedListJson.map<Item>((dynamic i) => Item.fromJson(i)));

其中 Item是您的自定义类,您在其中实现了 toJsonfromJson

我总是这样使用,没有问题;

List<MyModel> myModels;
var response = await http.get("myUrl");


myModels=(json.decode(response.body) as List).map((i) =>
MyModel.fromJson(i)).toList();

遵循以下步骤:

  1. 创建一个模型类(名为 LoginResponse) : 点击这里将 json 转换为 dart

  2. LoginResponce loginResponce=LoginResponce.fromJson(json.decode(response.body));

  3. 现在您可以在 model 的实例中获得数据(作为 loginResponse)。

这是我的模型类-

  class SuggestedMovie {
String title;
String genres;
int movieId;
SuggestedMovie({this.title, this.genres, this.movieId});
factory SuggestedMovie.fromJson(Map<dynamic, dynamic> parsedJson) {
return SuggestedMovie(
movieId: parsedJson['movieId'],
title: parsedJson['title'] as String,
genres: parsedJson['genres'] as String,
);
}
}

下面是将 JSON 响应反序列化为 List 的代码

 suggestedMovie = (json.decode(jsonResponse.data) as List)
.map((i) => SuggestedMovie.fromJson(i))
.toList();

返回文章页面如何在 Deserialize 找到 json in flutter 的物品清单

JSONSerializer反序列化。
代码生成示例:

import 'dart:io';


import 'package:object_serializer/json_serializer_generator.dart';
import 'package:yaml/yaml.dart';


void main() {
final classes = loadYaml(_classes) as Map;
final g = JsonSerializerGenerator();
final classesCode = g.generateClasses(classes);


final values = {
'classes': classesCode,
};


var source = g.render(_template, values);
source = g.format(source);
File('bin/stackoverflow.dart').writeAsStringSync(source);
}


const _classes = '''
Post:
fields:
userId: int
id: int
title: String
body: String
''';


const _template = r'''
import 'dart:convert';


import 'package:http/http.dart' as http;


void main() async {
final res1 =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
final post = Post.fromJson(jsonDecode(res1.body) as Map);
print(post.title);
final res2 =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
final posts = Post.fromJsonList(jsonDecode(res2.body) as List);
print('Posts: ${posts.length}');
if (posts.isNotEmpty) {
print(posts.first.title);
}
}


\{\{classes}}
''';

生成示例的源代码:

import 'dart:convert';


import 'package:http/http.dart' as http;


void main() async {
final res1 =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
final post = Post.fromJson(jsonDecode(res1.body) as Map);
print(post.title);
final res2 =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
final posts = Post.fromJsonList(jsonDecode(res2.body) as List);
print('Posts: ${posts.length}');
if (posts.isNotEmpty) {
print(posts.first.title);
}
}


class Post {
Post(
{required this.userId,
required this.id,
required this.title,
required this.body});


factory Post.fromJson(Map json) {
return Post(
userId: json['userId'] == null ? 0 : json['userId'] as int,
id: json['id'] == null ? 0 : json['id'] as int,
title: json['title'] == null ? '' : json['title'] as String,
body: json['body'] == null ? '' : json['body'] as String,
);
}


final int userId;


final int id;


final String title;


final String body;


static List<Post> fromJsonList(List json) {
return json.map((e) => Post.fromJson(e as Map)).toList();
}


Map<String, dynamic> toJson() {
return {
'userId': userId,
'id': id,
'title': title,
'body': body,
};
}


static List<Map<String, dynamic>> toJsonList(List<Post> list) {
return list.map((e) => e.toJson()).toList();
}
}

在强模式启用的情况下,由于缺少类型信息,上述解决方案都不会实际进行编译。

这是根据 dart 2.14编译的,启用了强模式:

Analysis _ options. yaml 分析 _ 选项


include: package:lints/recommended.yaml


analyzer:
strong-mode:
implicit-casts: false
implicit-dynamic: false


    import 'dart:convert';


// read the json file. This example use dcli but you just
// need [source] to contain the json string.
var source = dcli.read(_failedTrackerFilename).toParagraph();


var l = json.decode(source) as Iterable;
var failures = List<UnitTest>.from(l.map<UnitTest>(
(dynamic i) => UnitTest.fromJson(i as Map<String, dynamic>)));

完整的例子

下面是 反对列表 < 对象 > 的 JSON 序列化和反序列化的完整示例。这里我们有一个由嵌套的 三明治类和 列表 < 子 > 组成的 总部类。

杰森的样本

{
"title": "something",
"sub": {"name": "a", "num": 0},
"sub_list": [
{"name": "b", "num": 1},
{"name": "c", "num": 2}
]
}

主课

class Main {
String title;
Sub sub;
List<Sub> subList;


Main(this.title, this.sub, this.subList);


Main.fromJson(Map<String, dynamic> json)
: title = json['title'],
sub = Sub.fromJson(json['sub']),
subList = List<dynamic>.from(json['sub_list'])
.map((i) => Sub.fromJson(i))
.toList();


Map<String, dynamic> toJson() => {
'title': title,
'sub': sub.toJson(),
'sub_list': subList.map((item) => item.toJson()).toList(),
};
}

分班

class Sub {
String name;
int n;


Sub(this.name, this.n);


Sub.fromJson(Map<String, dynamic> json)
: name = json['name'],
n = json['n'];


Map<String, dynamic> toJson() => {
'name': name,
'n': n,
};
}

用途

void main(List<String> args) {
var sub = Sub("a", 0);
print(sub.name); // a


Map<String, dynamic> jsonSub = {"name": "a", "n": 0};
var subFromJson = Sub.fromJson(jsonSub);
print(subFromJson.n); // 0


var main = Main("something", Sub("a", 0), [Sub("b", 1)]);
print(main.title); // something
print(main.sub.name); // a
print(main.subList[0].name); // b


var jsonMain = {
"title": "something",
"sub": {"name": "a", "n": 0},
"sub_list": [
{"name": "b", "n": 1},
{"name": "c", "n": 2}
]
};
var mainFromJson = Main.fromJson(jsonMain);
print(mainFromJson.title); // something
print(mainFromJson.sub.name); // a
print(mainFromJson.subList[0].name); // b
print(mainFromJson.subList[1].name); // c
}

有时,JSON 的结构和 Pojo 类会出现问题。

我的 JSON 如下:

{"records":[{"name":"noor ","email":"email","mobileNo":187,"feedback":"good"}]}

根据这个 JSON,我们必须正确地创建 pojo 类。 当你粘贴你的 JSON 时,它会给你这个站点的 pojo 类: < a href = “ https://javiercbk.github.io/JSON _ to _ dart/”rel = “ nofollow norefrer”> https://javiercbk.github.io/json_to_dart/

你必须在那里给出一个类名。根据问题的名称,我根据上面的 JSON 找到了以下两个 pojo 类:

class Questions {
List<Records>? records;


Questions({this.records});


Questions.fromJson(Map<String, dynamic> json) {
if (json['records'] != null) {
records = <Records>[];
json['records'].forEach((v) {
records!.add(new Records.fromJson(v));
});
}
}


Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.records != null) {
data['records'] = this.records!.map((v) => v.toJson()).toList();
}
return data;
}
}


class Records {
String? name;
String? email;
int? mobileNo;
String? feedback;


Records({this.name, this.email, this.mobileNo, this.feedback});


Records.fromJson(Map<String, dynamic> json) {
name = json['name'];
email = json['email'];
mobileNo = json['mobileNo'];
feedback = json['feedback'];
}


Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['email'] = this.email;
data['mobileNo'] = this.mobileNo;
data['feedback'] = this.feedback;
return data;
}
}

现在重要的部分是: 将记录转换为列表:

Future<List<Records>> getRecordList() async {
return await http.get(Uri.parse(URL)).then((response) {
print(response.body.toString());


Questions questions = Questions.fromJson(json.decode(response.body));


     



print(questions.records![0].feedback);


List<Records> list_s = [];
for (int i = 0; i < questions.records!.length; i++) {
list_s.add(questions.records![i]);
}


print(list_s[0].name);


return list_s;
});
}
}

最后 UI 部分是:

class _FeedbackListPageState extends State<FeedbackListPage> {
 

List<Records> list_s = [];
  



@override
void initState() {
super.initState();


FormController().getRecordList().then((value) {
setState(() {
list_s = value;
});
});


    

}


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: darkGreen,
elevation: 0.0,
titleSpacing: 10.0,
title: Text(widget.title),
centerTitle: true,
leading: InkWell(
onTap: () {
Navigator.pop(context);
},
child: const Icon(
Icons.arrow_back_ios,
color: Colors.black54,
),
),
),
body: ListView.builder(
itemCount: list_s.length,
itemBuilder: (context, index) {
return ListTile(
title: Row(
children: <Widget>[
Icon(Icons.person),
Expanded(
child: Text("${list_s[index].name} (${list_s[index].email})"),
)
],
),
subtitle: Row(
children: <Widget>[
Icon(Icons.message),
Expanded(
child: Text(list_s[index].feedback.toString()),
)
],
),
);
},
),
);
}
}