在颤振中解析json
Posted
技术标签:
【中文标题】在颤振中解析json【英文标题】:Parsing a json in flutter 【发布时间】:2021-10-27 14:45:34 【问题描述】:我有这个从 firebase 实时数据库中获取的 json
[image: https://cdn.searchenginejournal.com/wp-content/uploads/2019/07/the-essential-guide-to-using-images-legally-online-1520x800.png, shopId: 1,
image: https://cdn.searchenginejournal.com/wp-content/uploads/2019/07/the-essential-guide-to-using-images-legally-online-1520x800.png, shopId: 2]
当我尝试解析它时,我收到了不同的错误: 第一种方式:
List<HomeSlider> posts = List<HomeSlider>.from(l.map((model)=> HomeSlider.fromJson(model)));
imgList.addAll(List<HomeSlider>.from(data.value) => HomeSlider.HomeSlider.fromJson(json));
第二种方式:
Map<dynamic, dynamic> yearMap = data.value;
yearMap.forEach((key, value)
imgList.add(HomeSlider.fromJson(value));
);
我有主滑块对象:
import 'package:json_annotation/json_annotation.dart';
/// This allows the `User` class to access private members in
/// the generated file. The value for this is *.g.dart, where
/// the star denotes the source file name.
part 'HomeSlider.g.dart';
@JsonSerializable()
class HomeSlider
HomeSlider(this.image, this.shopId);
String image="";
String shopId="";
/// A necessary factory constructor for creating a new User instance
/// from a map. Pass the map to the generated `_$UserFromJson()` constructor.
/// The constructor is named after the source class, in this case, User.
factory HomeSlider.fromJson(Map<String, dynamic> json) => _$HomeSliderFromJson(json);
/// `toJson` is the convention for a class to declare support for serialization
/// to JSON. The implementation simply calls the private, generated
/// helper method `_$UserToJson`.
Map<String, dynamic> toJson() => _$HomeSliderToJson(this);
错误是:
“String”不是“Map
我已经使用flutter CLI按照文档生成了类 有什么建议?谢谢
【问题讨论】:
错误是什么? 更新了问题以包含错误 您是否将 Json 作为字符串或映射首先:您的 Json 看起来不对,它缺少双引号:
["image": "https://cdn.searchenginejournal.com/wp-content/uploads/2019/07/the-essential-guide-to-using-images-legally-online-1520x800.png", "shopId": 1,
"image": "https://cdn.searchenginejournal.com/wp-content/uploads/2019/07/the-essential-guide-to-using-images-legally-online-1520x800.png", "shopId": 2]
第二: 在您的模型中 shopId 可能应该是一个 int。 如果打算使用字符串,您还需要将 id 放在双引号中。
然后使用 jsonDecode 将 String 转换为 List
List<HomeSlider> homeSliderList;
homeSliderList= (jsonDecode(yourJsonString) as List)
.map((i) => HomeSlider.fromJson(i))
.toList();
【讨论】:
jsonDecode(jsonEncode(content)) 我尝试对 json 进行编码,但仍然无法正常工作。我将发布不同的错误 Dart 未处理异常:FormatException:意外字符(在字符 2 处)。我认为从firebase返回的json有问题。出于某种原因,firebase 没有以正确的格式返回它 我之前只是对json字符串进行了编码。谢谢以上是关于在颤振中解析json的主要内容,如果未能解决你的问题,请参考以下文章