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

Share:
1,029
sgon00
Author by

sgon00

Updated on December 09, 2022

Comments

  • sgon00
    sgon00 over 1 year

    In Flutter doc, it uses jsonEncode(), while in Angular doc, it uses json.encode(). What is the difference and preferred way between the two?

  • sgon00
    sgon00 about 5 years
    Cool. 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
    sgon00 about 5 years
    oh, I finally get it why there is jsonEncode then. Thank you very much.
  • sgon00
    sgon00 about 5 years
    I 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
    jamesdlin about 5 years
    @sgon00 No worries! I'm glad I got to learn something too. =)