我从一个API接收一个JSON,并将其解析为一个类,如下所示:
class HappyModel {
HappyModel({
required this.id,
required this.name,
});
final String id;
final String name;
factory HappyModel.fromJson(Map<String, dynamic> _json) {
return HappyModel(
id: _json['_id'].toString(),
name: _json['name'].toString(),
);
}
}
字符串
- 以下是我的JSON格式(简化版):*
{
"_id":62348d85433322b995288b41,
"date":"2022-05-02T00":"00":00.000Z,
"name":"Happy Name",
"restaurant":{
"ticket":615ec9a2ec0a3a001d20abcf,
"opened":true,
"offers":{
"lunch":[
{
"_id":4051bae6df66a612ca5d008b,
"isOnlyForCustomer":false,
"price":750
},
{
"_id":5051bae6df66a612ca5d003a,
"isOnlyForCustomer":false,
"price":1000
},
{
"_id":6051bae6df66a612ca5d007e,
"isOnlyForCustomer":false,
"price":1150
}
],
"evening":[
{
"_id":1041bae6df66a612ca5d00ao,
"isOnlyForCustomer":false,
"price":1200
},
{
"_id":5051bae6df66a612ca5d000z,
"isOnlyForCustomer":false,
"price":750
},
{
"_id":8051bae6df66a612ca5d001a,
"isOnlyForCustomer":false,
"price":250
}
]
},
"something":null,
"somethingelse":"aoaoa"
}
}
型
我正在尝试访问嵌套在"restaurants" -> "offers" -> "lunch"
中的项目(优惠)
就像这样:
class HappyModel {
HappyModel({
required this.id,
required this.name,
required this.offers,
});
final String id;
final String name;
final List<OfferModel> offers;
factory HappyModel.fromJson(Map<String, dynamic> _json) {
return HappyModel(
id: _json['_id'].toString(),
name: _json['name'].toString(),
// Here ⭐️ I'd like to access the nested json
offers: OfferModel.listFromJson(_json['restaurants.offers.lunch']));
}
}
型
有没有关于如何直接访问嵌套在"restaurants" -> "offers" -> "lunch"
中的json数组的想法,而不需要创建一个餐厅模型等等?🙏
因为我不需要其他值
2条答案
按热度按时间eit6fx6z1#
访问
Map
的嵌套键的方法是多次调用[]
运算符:字符串
tkclm6bt2#
通过索引序列列表访问嵌套字段
字符串