【问题标题】:Parsing a json in flutter在颤振中解析json
【发布时间】: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”类型的子类型 或者如果我尝试对其进行编码,则会出现 w json 异常

我已经使用flutter CLI按照文档生成了类 有什么建议?谢谢

【问题讨论】:

  • 错误是什么?
  • 更新了问题以包含错误
  • 您是否将 Json 作为字符串或映射
  • 我从 firebase 作为字符串获取它。如何将从 firebase 接收到的数据解析为对象列表?

标签: json flutter firebase-realtime-database


【解决方案1】:

首先:您的 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字符串进行了编码。谢谢
猜你喜欢
  • 2019-01-17
  • 2021-08-23
  • 2020-03-01
  • 2021-09-25
  • 2021-02-25
  • 2020-09-12
  • 2023-03-05
  • 2021-11-04
  • 2019-09-06
相关资源
最近更新 更多