首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用json和串行化与火力基地和集团?错误:将对象转换为可编码对象失败

如何使用json和串行化与火力基地和集团?错误:将对象转换为可编码对象失败
EN

Stack Overflow用户
提问于 2019-06-22 06:39:56
回答 1查看 1.9K关注 0票数 1

这是我的云防火墙,看起来:

错误消息:未处理异常:将对象转换为可编码对象失败:摄影

我的数据库使用了jsonSerialization

代码语言:javascript
复制
import 'package:json_annotation/json_annotation.dart';
part 'Model.g.dart';

@JsonSerializable()
class Photography{
  String couplePhoto;
  String female;
  String image_url;
  String info;
  String male;
  AllImages all_images;

  Photography();

  factory Photography.fromJson(Map<String, dynamic> json) => _$PhotographyFromJson(json);
  Map<String,dynamic> toJson() => _$PhotographyToJson(this);
}

@JsonSerializable()
class AllImages {
  List<String> imageUrl = List<String>();

  AllImages();

  factory AllImages.fromJson(Map<String, dynamic> json) => _$AllImagesFromJson(json);
  Map<String,dynamic> toJson() => _$AllImagesToJson(this);
}

通过在项目根目录中运行flutter pub run build_runner build,每当需要照片和AllImages时,我都会为它们生成JSON序列化代码。

Model.g.dart

代码语言:javascript
复制
// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'Model.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Photography _$PhotographyFromJson(Map<String, dynamic> json) {
  return Photography()
    ..couplePhoto = json['couplePhoto'] as String
    ..female = json['female'] as String
    ..image_url = json['image_url'] as String
    ..info = json['info'] as String
    ..male = json['male'] as String
    ..all_images = json['all_images'] == null
        ? null
        : AllImages.fromJson(json['all_images'] as Map<String, dynamic>);
}

Map<String, dynamic> _$PhotographyToJson(Photography instance) =>
    <String, dynamic>{
      'couplePhoto': instance.couplePhoto,
      'female': instance.female,
      'image_url': instance.image_url,
      'info': instance.info,
      'male': instance.male,
      'all_images': instance.all_images
    };

AllImages _$AllImagesFromJson(Map<String, dynamic> json) {
  return AllImages()
    ..imageUrl = (json['imageUrl'] as List)?.map((e) => e as String)?.toList();
}

Map<String, dynamic> _$AllImagesToJson(AllImages instance) =>
    <String, dynamic>{'imageUrl': instance.imageUrl};

之后,我创建了DB类

如何使用模型类?

代码语言:javascript
复制
    class DB {
      final db = Firestore.instance;

     // Stream<QuerySnapshot> initStream() {
     //   return db.collection('photography').snapshots();
     // }

    getPhotography() async {
      return db.collection('photography')
        .document("0yUc5QBGHNNq6WK9CyyF")
        .setData(jsonDecode(jsonEncode(Photography)));
}
    }

    DB db = DB();

我的photography_bloc课程

代码语言:javascript
复制
class PhotographyBloc extends BlocBase{
  //PhotographyBloc(){
  //  db.initStream().listen((data) => inFirestore.add(data));
  //}
PhotographyBloc(){
  init();
}
Photography photography;

  //final _firestoreController = StreamController<Photography>();
  //Stream<Photography> get outFirestore => _firestoreController.stream;
  //Sink<Photography> get inFirestore => _firestoreController.sink;

    final _firestoreController = StreamController<Photography>();
    Stream<Photography> get outFirestore => _firestoreController.stream;
    Sink<Photography> get inFirestore => _firestoreController.sink;

  void init() async{
    photography = db.getPhotography();
    inFirestore.add(photography);
  }


  @override
  void dispose() {
    _firestoreController.close();
  }
}

如何使用StreamBuilder序列化获取数据

代码语言:javascript
复制
                    child: StreamBuilder<Photography>(
                        stream: bloc.outFirestore,
                        initialData: null,
                        builder: (context, snapshot) {
                          if (snapshot.hasData) {
                            return Column(
                                children: buildItem(snapshot.data, bloc));
//                                children: snapshot.data.documents
//                                    .map<Widget>((doc) => buildItem(doc, bloc))
//                                    .toList());
                          } else {
                            return SizedBox();
                          }
                        }),

builderItem()方法

代码语言:javascript
复制
buildItem(Photography doc, PhotographyBloc bloc) {
...
 child: ClipRRect(
                            borderRadius: BorderRadius.circular(20.0),
                            child: FadeInImage.assetNetwork(
                              placeholder: "assets/images/photography.jpg",
                              image: doc.couplePhoto,
//                              image: doc.data['couplePhoto'],
                              fit: BoxFit.fill,
                            ),
                          ),
EN

回答 1

Stack Overflow用户

发布于 2019-06-23 08:32:49

根据一揽子消息来源:

代码语言:javascript
复制
  /// Writes to the document referred to by this [DocumentReference].
  ///
  /// If the document does not yet exist, it will be created.
  ///
  /// If [merge] is true, the provided data will be merged into an
  /// existing document instead of overwriting.
  Future<void> setData(Map<String, dynamic> data, {bool merge = false}) {
    return Firestore.channel.invokeMethod<void>(
      'DocumentReference#setData',
      <String, dynamic>{
        'app': firestore.app.name,
        'path': path,
        'data': data,
        'options': <String, bool>{'merge': merge},
      },
    );
  }

必须将<String, dynamic>映射交给setData(x)方法。

所以在你的情况下,你也许应该这样做:

代码语言:javascript
复制
getPhotography() async {
      return db.collection('photography')
        .document("0yUc5QBGHNNq6WK9CyyF")
        .setData(photography.toJson());
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56713219

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档