我有一个JSON,如果其中一个属性的值不同,则返回一个重复的对象,例如:
{
"nid": "41",
"news_title": "title",
"body": "body",
"news_image": "img1.JPG",
},
{
"nid": "41",
"news_title": "title",
"body": "body",
"news_image": "img2.JPG",
},
它们都是ID为41的同一个节点,除了唯一的news_image以外,其他数据均重复了
对象的类是:
String nid;
String newsTitle;
String body;
String newsImage;
List<String> newsImgs;
并且正在像这样解析它:
List<News> newsdata = (jsonResponse as List).map((i) => new News.fromJson(i));
到目前为止一切都很好..但是我还有另外一个列表:
List<News> newsList = <News>[];
我要在其中将具有相同nid的相同新闻的图像添加到列表newsImgs,然后将其添加到newsList ..因此,我不会使用相同nid和相同新闻的所有图像复制新闻将在一个列表中
该怎么做?
答案 0 :(得分:0)
尝试列出此列表。 设置仅存储唯一值。
Set<News> newsList= new Set();
newsList.addAll(newsdata);
答案 1 :(得分:0)
import 'dart:convert';
import 'package:queries/collections.dart';
void main() {
var news = Collection(_readData());
var query = news
.select((m) => News.fromMap(m)
..newsImgs = news
.where((n) => n['nid'] == m['nid'])
.select((n) => n['news_image'] as String)
.toList())
.distinct(CustomEqualityComparer((e1, e2) => e1.nid == e2.nid, (n) => 0));
print(query.toList());
}
var _data = '''
[
{
"nid": "41",
"news_title": "title",
"body": "body",
"news_image": "img1.JPG"
},
{
"nid": "41",
"news_title": "title",
"body": "body",
"news_image": "img2.JPG"
},
{
"nid": "42",
"news_title": "title",
"body": "body",
"news_image": "img3.JPG"
}
]
''';
List _readData() {
return jsonDecode(_data);
}
class News {
String nid;
String newsTitle;
String body;
String newsImage;
List<String> newsImgs;
News.fromMap(Map data) {
body = data['body'] as String;
nid = data['nid'] as String;
newsImage = data['news_image'] as String;
newsTitle = data['news_title'] as String;
}
String toString() {
return 'nid: ${nid}, images: ${newsImgs}';
}
}
结果:
[nid: 41, images: [img1.JPG, img2.JPG], nid: 42, images: [img3.JPG]]
另一种方式(通过分组):
void main() {
var news = Collection(_readData());
var query = news.groupBy$2(
(m) => m['nid'] as String,
(k, v) => News.fromMap(v.firstOrDefault())
..newsImgs = v.select((e) => e['news_image'] as String).toList());
print(query.toList());
}
要导入软件包queries
,您需要在文件pubspec.yaml
中添加以下行:
dependencies:
queries: ^0.1.12