flutter 序列化

If you intend to save user data to the shared preferences or local storage in your Flutter application, you will need to serialize it manually.

如果打算将用户数据保存到Flutter应用程序中的共享首选项或本地存储中,则需要手动对其进行序列化。

This is because both methods only support a limited selection of primitive object types and your object will probably not fall into any category. To do this we will be using the dart:convert decoder with its jsonEncode/jsonDecode methods, so make sure to import it into your project.

这是因为这两种方法仅支持有限的原始对象类型选择,并且您的对象可能不会属于任何类别。 为此,我们将使用dart:convert解码器及其jsonEncode / jsonDecode方法,因此请确保将其导入到您的项目中。

To do this, import the class in your main dart file:

为此,将类导入到您的主dart文件中:

import 'dart:convert';

如何在Dart中建立模型类 (How to build a Model Class in Dart)

To allow our object to become enabled for decoding/encoding we first need to create a Model class for it. This class will represent the object and it’s fields and have the important methods which will do the heavy work of encoding/decoding. The first one is called fromJson and the second one is called toJson. We will show various examples of complex objects and how to serialize them, but for the beginning, we’ll start with a simple one.

为了使我们的对象能够进行解码/编码,我们首先需要为其创建一个Model类。 此类将表示对象及其字段,并具有将进行繁重的编码/解码工作的重要方法。 第一个称为fromJson ,第二个称为toJson 。 我们将展示复杂对象的各种示例以及如何序列化它们,但首先,我们将从一个简单的示例开始。

We’ll imagine we have a doughnut shop, where we have various doughnuts. Each doughnut is an object that contains the following keys:

我们将想象我们有一家甜甜圈店,那里有各种甜甜圈。 每个甜甜圈都是一个包含以下键的对象:

  • Name - String名称-字串
  • Filling - String填充-字符串
  • Topping - String打顶-字符串
  • Price - Double价格-双倍

In Dart, it would like this:

在Dart中,它是这样的:

class Doughnut {final String name;final String filling;final String topping;final double price;Doughnut(this.name, this.filling, this.topping, this.price);Doughnut.fromJson(Map<String, dynamic> json): name = json['name'],filling = json['filling'],topping = json['topping'],price = json['price'];Map<String, dynamic> toJson() => {'name' : name,'filling' : filling,'topping' : topping,'price' : price};
}

You may have noticed a weird type in there called dynamic. Dynamic signifies an unknown type in the dart language, one which will be realized during runtime. Think of it as similar to the Object type in Java, which all types inherit from. Any object can be cast into dynamic to invoke methods on it. If no type is declared for a variable or a return type for a method, it is assumed to be dynamic.

您可能已经注意到其中有一种叫做dynamic的怪异类型。 动态表示Dart语言中的未知类型,该类型将在运行时实现。 可以认为它类似于Java中所有类型都继承自的对象类型。 任何对象都可以转换为动态对象以调用其上的方法。 如果没有声明变量的类型或方法的返回类型,则假定它是动态的。

如何在Flutter中对数据进行序列化和反序列化 (How to Serialize and De-Serialize Data in Flutter)

Now that we have our model class, we can use it to serialized and de-serialize our data. Below is an example of just how to do that.

现在我们有了模型类,我们可以使用它来对数据进行序列化和反序列化。 以下是如何执行此操作的示例。

Creating a doughnut object is simple:

创建一个甜甜圈对象很简单:

Doughnut myDoughnut = new Doughnut("Glazed", "None", "Sprinkles", 2.99);

And now we can serialize it by using jsonEncode:

现在我们可以使用jsonEncode对其进行序列化:

String encodedDoughnut = jsonEncode(myDoughnut);

Under the hood, jsonEncode calls our own toJson method that we created in our doughnut model class. The same also applies for jsonDecode as it calls the fromJson method.

在后台,jsonEncode调用我们自己的在donut模型类中创建的toJson方法。 jsonDecode也是如此,因为它调用fromJson方法。

In string form, our doughnut object, now looks like this:

以字符串形式,我们的甜甜圈对象现在看起来像这样:

{"name":"Glazed","filling":"None","topping":"Sprinkles","price":2.99}

And after we decode it,

在我们解码之后

Map<String, dynamic> decodedDoughnut = jsonDecode(encodedDoughnut);

we will get:

我们将获得:

{name: Glazed, filling: None, topping: Sprinkles, price: 2.99}

Did you notice the subtle differences?

您注意到细微的差异了吗?

The decoded object is now a Map with keys of string type and values of dynamic type. If we want to convert this data type back to our original object, we need to access the properties of the map:

现在,已解码的对象是一个Map,其中包含字符串类型的键和动态类型的值。 如果要将此数据类型转换回我们的原始对象,则需要访问地图的属性:

Doughnut newDoughnut = new Doughnut(decodedDoughnut["name"], decodedDoughnut["filling"], decodedDoughnut["topping"], decodedDoughnut["price"]);

如何在Dart中序列化数组 (How to Serialize Arrays in Dart)

Life is not as simple as a doughnut(if only, right?), so we have to take into account that we won’t always be dealing with parameter types that are simple. Let’s assume that the toppings field is not a String, but is an Array of strings. First, let’s redefine the toppings field:

生活并不像甜甜圈那么简单(如果只有,是吧?),因此我们必须考虑到,我们将不会总是处理简单的参数类型。 假设toppings字段不是String,而是字符串数组。 首先,让我们重新定义浇头字段:

String topping => List<String> toppings;

Then, in our fromJson method we will have to do the following:

然后,在我们的fromJson方法中,我们将必须执行以下操作:

Doughnut.fromJson(Map<String, dynamic> json) {name = json['name'];filling = json['filling'];var toppingsFromJson = json['toppings'];toppings = new List<String>.from(toppingsFromJson);price = json['price'];}

Notice, how we have a temporary variable to first extract the value from the json variable and then we explicitly convert the value to our toppings list original type. We have to do this since at first, the type for the value of toppings is dynamic and dart does not know which type it is explicitly.

请注意,我们如何拥有一个临时变量以首先从json变量中提取值,然后将其显式转换为浇头列表原始类型。 我们必须这样做,因为起初,浇头值的类型是动态的,而dart不知道它是哪种类型。

复杂物体 (Complex Objects)

No one ever buys only one doughnut, right? That would be useless. Let’s imagine we have a dozen. So now we are dealing with a list of objects of Doughnut type. To serialize/de-serialize a list of objects we will use the model class above, but we will need to create a different model class to handle the list.

没有人只买一个甜甜圈,对吗? 那将是无用的。 假设我们有一打。 因此,现在我们正在处理“甜甜圈”类型的对象列表。 要序列化/反序列化对象列表,我们将使用上面的模型类,但是我们将需要创建一个不同的模型类来处理该列表。

import 'package:serialization_example/models/doughnut.dart';class DoughnutList {final List<Doughnut> doughnuts;DoughnutList(this.doughnuts);DoughnutList.fromJson(Map<String, dynamic> json): doughnuts = json['doughnuts'] != null ? List<Doughnut>.from(json['doughnuts']) : null;Map<String, dynamic> toJson()  =>{'doughnuts': doughnuts,};}

As you can see, we now have a model class that has a field of type List that holds Doughnut objects.

如您所见,我们现在有了一个模型类,该模型类具有一个包含Donut对象的List类型的字段。

Similar to the example above, to serialize the object we use the jsonEncode method and when we want to decode the object we have to perform the following:

与上面的示例类似,要序列化对象,我们使用jsonEncode方法,当我们想对对象进行解码时,我们必须执行以下操作:

Map<String, dynamic> decodedDoughnuts = jsonDecode(encodedJson);
List<dynamic> decodedJson =  decodedDoughnuts['doughnuts'];
decodedJson.map((elem) => jsonDecode(elem));

To see all that we covered in this article, head over to the repository on GitHub.

要查看我们在本文中介绍的所有内容,请转到GitHub上的存储库 。

翻译自: https://www.freecodecamp.org/news/serialize-object-flutter/

flutter 序列化

flutter 序列化_如何在Flutter中序列化对象相关推荐

  1. java构造方法的签名_如何在 Java 中构造对象(学习 Java 编程语言 034)

    1. 构造器 Java 对象都是在堆中构造的. 先看看 Employee 类的构造器: public class Employee { private String name; private dou ...

  2. java对象数组排序_如何在Java中对对象数组进行排序?

    小编典典 你有两种方法可以使用Arrays实用程序类 实现一个Comparator并将数组与比较器一起传递给sort方法,该方法将其作为第二个参数. 在对象所属的类中实现Comparable接口,并将 ...

  3. figma设计_如何在Figma中构建设计入门套件(第1部分)

    figma设计 Figma教程 (Figma Tutorial) Do you like staring at a blank canvas every time you start a new pr ...

  4. 在excel日期比对大小_如何在Excel中防止分组日期

    在excel日期比对大小 As a teenager, group dates can be fun. If you have strict parents, that might be the on ...

  5. 表格在整个html居中显示,html 表格字符居中显示_如何在HTML中居中显示表格?

    html 表格字符居中显示_如何在HTML中居中显示表格? html 表格字符居中显示_如何在HTML中居中显示表格? html 表格字符居中显示 HTML table provides the ab ...

  6. 如何在Javascript中访问对象的第一个属性?

    本文翻译自:How to access the first property of an object in Javascript? Is there an elegant way to access ...

  7. flutter调用api_如何在Flutter(REST API)中进行API调用

    flutter调用api 在本文中,我们将看一下如何快速进行API调用并使用简单的REST API. 在这里查看我在Flutter上的其他一些帖子: Flutter vs React Native 了 ...

  8. keypair java_如何在Java中序列化和反序列化RSA KeyPair

    我想在我的Java应用程序中实现一些非常基本的安全性,但是一开始我就陷入了困境. 我想做的是这样的: 1-生成RSA密钥对 2将这些密钥以序列化形式存储在数据库中,以便在下次运行该应用程序时重新创建它 ...

  9. django 传递中文_如何在Django中建立消息传递状态

    django 传递中文 by Ogundipe Samuel 由Ogundipe Samuel 如何在Django中建立消息传递状态 (How to Build a Message Delivery ...

最新文章

  1. 最新批量***dedecms|dedecms最新0day
  2. NodeJs教程(介绍总结!)终于在网上找到一个靠谱点的了T_T
  3. Python语言学习:python编程之pip命令集合、python调式、头部代码、代码运行等常见概念详细攻略(解决问题为导向)
  4. 关于c++ template的branching和Recursion的一段很好的描述
  5. 简单的计时器实现(JFrame)
  6. linux下安装python(安装python 3.6稳定版成功亲测)
  7. latex中的对号和错号
  8. Java数据结构——二叉树
  9. 正规word文档文件字体排版格式要求(标准)
  10. Rails进阶——框架理论认知与构建方案建设(一)
  11. win10和win8双系统安装
  12. AS400 资料大放送
  13. Visual Studio中Git的使用(完全图解)
  14. 小鹏汽车领投 这家车规级MEMS激光雷达公司完成数亿元Pre-C轮融资
  15. Linux运维——文件系统管理
  16. 全排列-python递归解法
  17. 使用Eclipse开发Python
  18. mysql dwith boost_【云知梦】CentOS8.2上如何编译安装MySQL8?
  19. Python中十进制与其它进制之间的相互转换
  20. Java 汉字拆分转为拼音 及根据经纬度获取所在位置

热门文章

  1. 大连印象_2010暑期实训有感【一】
  2. 修改线程的名称 java 1615387415
  3. 打开文件对话框的演练 c# 1614821885
  4. 190916-二级format补齐
  5. python-函数的位置参数
  6. Sql Server cdc变更捕获使用
  7. JAVA面试考点解析(12) -- 算法
  8. Symfony 框架实战教程——第一天:创建项目(转)
  9. centsos7修改主机名 [root@st152 ~]# cat /etc/hostname
  10. java基础----数据类型转化