对Flutter中的对象进行JSON序列化和反序列化 [英] JSON serialization and deserialization to objects in Flutter

查看:101
本文介绍了对Flutter中的对象进行JSON序列化和反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Flutter从其SDK中删除了dart:mirrors,因此不再可以将dartson之类的库用于JSON进行对象序列化/反序列化.但是,我读到build_value是实现类似目的的另一种方法.我找不到任何有关如何实现它的好的示例,因为它包含大量的样板代码.有人可以给我一个例子吗?例如,这是我要序列化为对象的JSON:

Since Flutter took out dart:mirrors off of its SDK, it's no longer possible to use libraries like dartson for JSON to object serialization/deserialization. However I've read that built_value is another way of achieving a similar purpose. I couldn't find any good examples on how to implement it as it contains a significant amount of boiler plate code. Can someone give me an example? For instance, this is the JSON I'm trying to serialize to objects:

{
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
        { "name":"BMW", "models":[ "320", "X3", "X5" ] },
        { "name":"Fiat", "models":[ "500", "Panda" ] }
    ]
 }

推荐答案

我希望从提供的答案中获得更多详细信息.尽管它们是很好的建议,但对于我来说它们太笼统了.因此,在进行了自己的研究之后,我将与上面提供的JSON示例共享我的实现,希望它可以节省其他人的时间.所以这是我遵循的步骤:

I was hoping for more details from the answers provided. Even though they were good suggestions, they were too general for me to understand. So after doing my own research, I'll share my implementation to the above JSON example I provided in hope that it would save someone's else's time. So here are the steps I followed:

  • 在我的Flutter项目中,首先我导入了以下库:

依赖项:

内置值:^ 1.0.1
built_collection:^ 1.0.0

built_value: ^1.0.1
built_collection: ^1.0.0

dev_dependencies:

dev_dependencies:

build_runner:^ 0.3.0
Built_value_generator:^ 1.0.1

build_runner: ^0.3.0
built_value_generator:^1.0.1

  • 我创建了一个名为tool的文件夹.在其中,我放入了两个文件:build.dart和watch.dart.这些文件的实现如下所示
  • build.dart

    build.dart

    // Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details.
    // All rights reserved. Use of this source code is governed by a BSD-style
    // license that can be found in the LICENSE file.
    
    import 'dart:async';
    
    import 'package:build_runner/build_runner.dart';
    import 'package:built_value_generator/built_value_generator.dart';
    import 'package:source_gen/source_gen.dart';
    
    /// Example of how to use source_gen with [BuiltValueGenerator].
    ///
    /// Import the generators you want and pass them to [build] as shown,
    /// specifying which files in which packages you want to run against.
    Future main(List<String> args) async {
      await build(
          new PhaseGroup.singleAction(
              new GeneratorBuilder([new BuiltValueGenerator()]),
              new InputSet('built_value_example', const [
                'lib/model/*.dart',
                'lib/*.dart',
              ])),
          deleteFilesByDefault: true);
    }
    

    watch.dart

    watch.dart

    // Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details.
    // All rights reserved. Use of this source code is governed by a BSD-style
    // license that can be found in the LICENSE file.
    
    import 'dart:async';
    
    import 'package:build_runner/build_runner.dart';
    import 'package:built_value_generator/built_value_generator.dart';
    import 'package:source_gen/source_gen.dart';
    
    /// Example of how to use source_gen with [BuiltValueGenerator].
    ///
    /// This script runs a watcher that continuously rebuilds generated source.
    ///
    /// Import the generators you want and pass them to [watch] as shown,
    /// specifying which files in which packages you want to run against.
    Future main(List<String> args) async {
      watch(
          new PhaseGroup.singleAction(
              new GeneratorBuilder([new BuiltValueGenerator()]),
              new InputSet('built_value_example', const [
                'lib/model/*.dart',
                'lib/*.dart'])),
          deleteFilesByDefault: true);
    }
    

    • 我创建了一个serializers.dart文件,该文件会将我的json字符串序列化为我的自定义dart对象和模型对象person.dart
    • serializers.dart

      serializers.dart

      library serializers;
      
      import 'package:built_collection/built_collection.dart';
      import 'package:built_value/serializer.dart';
      import 'package:built_value/standard_json_plugin.dart';
      import 'model/person.dart';
      
      part 'serializers.g.dart';
      
      Serializers serializers = (
          _$serializers.toBuilder()..addPlugin(new StandardJsonPlugin())
      ).build();
      

      person.dart

      person.dart

      library person;
      
      import 'package:built_collection/built_collection.dart';
      import 'package:built_value/built_value.dart';
      import 'package:built_value/serializer.dart';
      
      part 'person.g.dart';
      
      abstract class Person implements Built<Person, PersonBuilder> {
        String get name;
        int get age;
        BuiltList<Car> get cars;
      
        Person._();
        factory Person([updates(PersonBuilder b)]) = _$Person;
        static Serializer<Person> get serializer => _$personSerializer;
      }
      
      abstract class Car implements Built<Car, CarBuilder> {
        String get name;
        BuiltList<String> get models;
      
        Car._();
        factory Car([updates(CarBuilder b)]) = _$Car;
        static Serializer<Car> get serializer => _$carSerializer;
      }
      

      • 创建上面的4个文件之后,它将显示一些编译器错误.还不介意他们.这是因为build.dart文件尚未运行.因此,在此步骤中,运行build.dart.如果您使用的是Webstorm,只需右键单击build.dart并单击运行build.dart".这将创建2个文件:"person.g.dart"和"serializers.g.dart".如果您仔细注意,在我们的build.dart文件中,我们将'lib/model/ .dart'和'lib/ .dart'放入.该构建通过遍历指定的路径知道在哪里查找那些文件,并查找包含某些内容"的文件.因此,在运行build.dart文件之前,请务必将该行保留在这些文件中

        • After creating the 4 files above, it will show some compiler errors. Don't mind them yet. This is because the build.dart file hasn't been run yet. So in this step, run build.dart. If you're using Webstorm, simply right click on build.dart and hit "Run build.dart". This will create 2 files: "person.g.dart" and "serializers.g.dart". If you notice carefully, in our build.dart file, we put 'lib/model/.dart' and 'lib/.dart'. The build knows where to look for those files by going through the paths specified and looks for files which have part "something" included. So it's important to keep that line in those files before running the build.dart file

          最后,现在我可以在main.dart文件中使用序列化程序将json字符串序列化为我的自定义dart对象类Person.在main.dart中,我在initState()中添加了以下代码

          Finally, now I can use the serializer in my main.dart file to serialize the json string to my custom dart object class Person. In my main.dart, I added the following code in initState()

          main.dart

          main.dart

            Person _person;
          
            @override
            void initState() {
              super.initState();
              String json = "{"
                  "\"name\":\"John\",\"age\":30,\"cars\": "
                  "["
                  "{ \"name\":\"Ford\", \"models\":[ \"Fiesta\", \"Focus\", \"Mustang\" ] },"
                  "{ \"name\":\"BMW\", \"models\":[ \"320\", \"X3\", \"X5\" ] },"
                  "{ \"name\":\"Fiat\", \"models\":[ \"500\", \"Panda\" ] }"
                  "]}";
          
              setState(() {
                _person = serializers.deserializeWith(
                    Person.serializer, JSON.decode(json));
              });
            }
          

          我的示例项目也可以在Github上获得内置值示例项目

          My sample project is also available on Github Built value sample project

          这篇关于对Flutter中的对象进行JSON序列化和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆