Json is one of the essential foundational skills during development. Here’s how to parse JSON into instance objects and convert instance objects into JSON strings in the Dart language.
The tool used here is the DART: Convert package.
Our purpose is simple, the json string format to parse is as follows:
{
"key":"wangdandan"."value":"The father of the king's balls."
}
Copy the code
Json strings are parsed into instance objects
Create a model object
class JsonModelDemo {
String key;
String value;
}
Copy the code
2. Parse the entity class object into a JSON string.
We create an instance object, assign a value to the instance object, and parse the instance object using the jsonDecode method. The code is as follows,
import 'dart:convert';
import 'package:dart_demo1/json/json_model.dart'; GeneratePlatformJson ({String key, String value}) { JsonModelDemo jsonModelDemo = new JsonModelDemo(); jsonModelDemo.key = key; jsonModelDemo.value = value; String jsonStr = jsonEncode(jsonModelDemo);returnjsonStr; } /// write the test method heremain() {
String result1 = generatePlatformJson(key: "result1", value: "result1Value");
print('result1:$result1');
}
Copy the code
The following error occurs when executing the code:
lib/json/json_parse_util.dart:1: Warning: Interpreting this as package URI, 'package:dart_demo1/json/json_parse_util.dart'.
Unhandled exception:
Converting object to an encodable object failed: Instance of 'JsonModelDemo'
#0 _JsonStringifier.writeObject (dart:convert/json.dart:645:7)
#1 _JsonStringStringifier.printOn (dart:convert/json.dart:832:17)
#2 _JsonStringStringifier.stringify (dart:convert/json.dart:817:5)
#3 JsonEncoder.convert (dart:convert/json.dart:253:30)
#4 JsonCodec.encode (dart:convert/json.dart:164:45)
#5 jsonEncode (dart:convert/json.dart:76:10)
#6 generatePlatformJson (package:dart_demo1/json/json_parse_util.dart:10:20)
#7 main (package:dart_demo1/json/json_parse_util.dart:16:20)
#8 _startIsolate.
(dart:isolate/runtime/libisolate_patch.dart:300:19)
#9 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
Process finished with exit code 255
Copy the code
Converting Object to an encodable object failed: The Instance of ‘XXX’ this mistake, find the answer on stackoverflow: stackoverflow.com/questions/2…
We add the toJson method to the Model entity class:
class JsonModelDemo { String key; String value; /// This method of the entity class is called in the jsonDecode(jsonStr) method. If the method does not exist in the entity class, an error is reported. MaptoJson() {
Map map = new Map();
map["key"] = this.key;
map["value"] = this.value;
returnmap; }}Copy the code
This time, the code is parsed successfully, and the output is as follows:
result1:{"key":"result1"."value":"result1Value"}
Copy the code
The instance object is converted to a JSON string
The parse code is as follows:
JsonModelDemo parsePlatformJson(String jsonStr) {JsonModelDemo result = jsonDecode(jsonStr);return result;
}
Copy the code
The test code is as follows:
JsonModelDemo modelDemo = parsePlatformJson(result1);
print('parsePlatformJson:$modelDemo');
Copy the code
To facilitate testing, the toString method is overridden in JsonModelDemo;
@override
String toString() {
return 'JsonModelDemo{key: $key, value: $value}';
}
Copy the code
Run the code, the error is as follows:
Unhandled exception:
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'JsonModelDemo'
#0 parsePlatformJson (package:dart_demo1/json/json_parse_util.dart:16:17)
#1 main (package:dart_demo1/json/json_parse_util.dart:25:29)
#2 _startIsolate.
(dart:isolate/runtime/libisolate_patch.dart:300:19)
#3 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
Copy the code
The jsonDecode method returns Map<String, dynamic>, not the desired instance object. So, we also need to convert Map<String, dynamic> into the instance object we want.
Add transformation methods to model:
/// jsonDecode(jsonStr) returns Map<String, dynamic>, Static JsonModelDemo fromMap(map <String, dynamic> map) { JsonModelDemo jsonModelDemo = new JsonModelDemo(); jsonModelDemo.key = map['key'];
jsonModelDemo.value = map['value'];
return jsonModelDemo;
}
Copy the code
Next change the parsing method:
JsonModelDemo parsePlatformJson(String jsonStr) {JsonModelDemo result = JsonModelDemo.fromMap(jsonDecode(jsonStr));return result;
}
Copy the code
Run the code, parse successfully, output is as follows:
result1:{"key":"result1"."value":"result1Value"}
parsePlatformJson:JsonModelDemo{key: result1, value: result1Value}
Copy the code
Reference:
Stackoverflow.com/questions/2…
www.dartlang.org/guides/libr…
Medium.com/flutter-com…