What is the difference and preferred way between jsonEncode() and json.encode() in Dart?
1,029
Solution 1
jsonEncode
as alias for json
was introduced because json
often collided with a varible name json
many used for the variable that holds the JSON value.
var json = http.get(...);
var data = json.decode(json); // error
var data = jsonDecode(json); // ok
Solution 2
There is no difference. From the the dart:convert
docs for jsonEncode
:
Shorthand for
json.encode
.
Solution 3
In the upcoming Sound Null-Safety update, currently in beta, the alias jsonEncode
does not work, so just use json.encode
Author by
sgon00
Updated on December 09, 2022Comments
-
sgon00 over 1 year
In Flutter doc, it uses
jsonEncode()
, while in Angular doc, it usesjson.encode()
. What is the difference and preferred way between the two? -
sgon00 about 5 yearsCool. Thanks a lot for the quick answer. I checked the doc before, but didn't realize the "shorthand" words. Due to time limitation, I can only accept the answer after 9 minutes.
-
sgon00 about 5 yearsoh, I finally get it why there is jsonEncode then. Thank you very much.
-
sgon00 about 5 yearsI was about to mark your post as the answer, but after seeing Günter Zöchbauer's answer, I think that clarifies why dart introduces a new shorthand at the first place. Sorry that I will mark his post as the answer since that is more clear to me. And I have upvoted your answer and Thank you very much for your quick reply, detail answer and well structured content.
-
jamesdlin about 5 years@sgon00 No worries! I'm glad I got to learn something too. =)