The business scenarios covered in this article
As long as our app is not stand-alone, it must involve remote server data requests. There is already a package called Dio for making requests in Flutter, which is very simple and easy to use. If you are not familiar with flutter, you can click on the dio documentation.
After making the request and getting the JSON data back from the server, what are the next steps? Flutter (Dart, I should say) is not inherently json friendly like javascript. This is the main content of this article. You will learn:
flutter
projectjson
Detailed steps of data processing and reminders of tread pits- in
json_serializable
Link, command line + tools, help you automatically generate relevant code, no hand typing, no hand typing (important things to say twice) - Data and source code are ready for you, no hand knocking (even small white, also easy to use)
Json data reading and processing
After requesting the data back, the next step must be to read the data information, and then proceed with the interface display and logical processing.
If the returned data is simple and the business logic is simple, the processing can be simplified as well. For example, the server returns the following data:
{
code: 200,
message: null,
value: true
}
Copy the code
Well, you could even do this:
if (jsonStr.indexOf('true')! = 1) {/ /do something
}
Copy the code
In conclusion, it is a good idea to use regular expression matching or simple string processing logic for a quick and simple implementation in this scenario.
Json deserialization
However, when the data structure is sufficiently complex (for example, click to see an example of complex data), the above approach is obviously a bit overstretched.
This is where the focus of this article, JSON deserialization, comes in. For serialization and deserialization, you can do a lot of research on the Internet (I really don’t want to look it up, ok, here it is, click serialization to make do…). .
Under the business scenario described in this paper, it can also be simply understood as: What we need to do is to convert the server-side JSON string data obtained through DIO into objects, and then we can happily access the field values in the objects.
There are two main steps:
json
String conversion toMap
object- use
json_serializable
Deserialize
The specific steps are as follows:
- Add the dependent
Refer to the following code to add the jSON_ANNOTATION, jSON_serialIZABLE, and Build_Runner packages to the pubspec.yaml file.
Dependencies: flutter: SDK: flutter json_annotation: ^3.0.0 dev_dependencies: flutter_test: SDK: Flutter json_serialIZABLE: ^3.2.0 build_runner: ^1.6.5Copy the code
Remember to add flutter packages get
- useOnline code generation toolsGenerate the JSON into dart code named
xxxx.dart
(File 1, referenced in the code below)copy to the project
If you’ve read other articles, you’ll probably be asked to write a Dart entity class based on JSON data, but you can do it any way you like. This article recommends tool generation, convenient and fast, not easy to error, ha ha…
If you don’t have the json data ready to experiment with, click on the sample data provided in this article, copy it into the tool, and have fun.
- Run in the directory of the current project
flutter packages pub run build_runner build
, command execution is complete according to the abovexxxx.dart
generatexxxx.g.dart
(After the file is generated, do not manually modify, do not need to reference, just leave it) - Start coding
import 'dart:convert';
import 'package:xxxxxxx/xxxx.dart'; // Import the file mentioned above -- String jsonStr ='{"value":1}'; Map<String,dynamic> Map = json.decode(jsonStr); Obj = myObject.fromjson (Map); // Suppose the class name is MyObjectprint(obj.value);
Copy the code
At this point, data deserialization is basically complete. In the above code, there are two main steps:
- String to Map
- Map to MyObject
MyObject is the class name in the imported file 1, which can be adjusted based on the actual situation.
You may also have a question, since the native already provides String to Map, so just do this step, and then use the Map object for the next coding, ok?
Actually, it’s possible, but… , here is an example of a comparison, it will be clear. Using this data example, the following two lines of code access the same fields:
print(homePageList.value[0].modules[0].items[1].title);
print(map.entries.elementAt(2).value[0].entries.elementAt(5).value[0].entries.elementAt(11).value[1].entries.elementAt(0).val ue);Copy the code
I don’t know which way you like…
Complex irregular data processing
Following the above steps, you can basically process most of the rule data, but when you use the data example as the data source and perform coding step by step to access the values of some of the fields, unexpected things happen:
print(homePageList.value[0].modules[0].items[1].title); // Print normallyprint(homePageList.value[0].modules[2].items[0].name); / / an errorCopy the code
Error message:
The following NoSuchMethodError was throw building BlockRowFrame(dirty):
Class 'Modules' has no instance getter 'title'.Copy the code
This is because the structure of each item of data is inconsistent. In the data example, the field name is not present in the items element of the first two modules, but it is present in the items element of the third module.
In this case, you just need to manually add the corresponding field code to the corresponding class in the “file 1” generated by the tool. Run flutter Packages pub run build_runner build — delete-Conflicting -outputs again.
This concludes the discussion about flutter JSON data processing and sharing. Code word is not easy, feel that this article is helpful to you, trouble point to encourage encouragement.
Afterword.
If there’s anything unclear…
Github project: “JSON format request result deserialization and use (DIO & JSON_serializable Demo)”