Explicitly parse JSON string vs JSON.deserialize The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Moderator Election Q&A - Questionnaire 2019 Community Moderator Election ResultsJSON and escaped double quoteParse nested JSONJSON parsing to Visualforce page difficultiesDefault values for Wrapper variables not setConvert date in JSON to Date from StringMethod does not exist or incorrect signature: void parse(String) from the type or_propertyJSONTestHow to parse JSON String through apexDeserializing/Parsing the JSON response to an Apex classJson2apex - Message consuming unrecognized propertyParse JSON using APEX provided JSON Methods

Is above average number of years spent on PhD considered a red flag in future academia or industry positions?

"... to apply for a visa" or "... and applied for a visa"?

how can a perfect fourth interval be considered either consonant or dissonant?

First use of “packing” as in carrying a gun

Take groceries in checked luggage

Would an alien lifeform be able to achieve space travel if lacking in vision?

Derivation tree not rendering

Hiding Certain Lines on Table

Is it ethical to upload a automatically generated paper to a non peer-reviewed site as part of a larger research?

Are my PIs rude or am I just being too sensitive?

What can I do if neighbor is blocking my solar panels intentionally?

What aspect of planet Earth must be changed to prevent the industrial revolution?

Do warforged have souls?

Difference between "generating set" and free product?

Keeping a retro style to sci-fi spaceships?

Match Roman Numerals

ELI5: Why do they say that Israel would have been the fourth country to land a spacecraft on the Moon and why do they call it low cost?

Problems with Ubuntu mount /tmp

Finding the path in a graph from A to B then back to A with a minimum of shared edges

How does ice melt when immersed in water?

I could not break this equation. Please help me

Why does this iterative way of solving of equation work?

Can withdrawing asylum be illegal?

In horse breeding, what is the female equivalent of putting a horse out "to stud"?



Explicitly parse JSON string vs JSON.deserialize



The 2019 Stack Overflow Developer Survey Results Are In
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
2019 Moderator Election Q&A - Questionnaire
2019 Community Moderator Election ResultsJSON and escaped double quoteParse nested JSONJSON parsing to Visualforce page difficultiesDefault values for Wrapper variables not setConvert date in JSON to Date from StringMethod does not exist or incorrect signature: void parse(String) from the type or_propertyJSONTestHow to parse JSON String through apexDeserializing/Parsing the JSON response to an Apex classJson2apex - Message consuming unrecognized propertyParse JSON using APEX provided JSON Methods



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















The JSON2Apex web tool offers 2 methods of parsing of the JSON string: one uses JSON.deserialize method, and the other creates parser and iterates over the input json. The second option can be enabled by checking "Create explicit parse code" in the tool.



QUESTION



In what cases would a developer prefer explicit parsing to a simple JSON.deserialize? If we compare both options the later seems to be much clear and less verbose which makes code more readable.



Explicit parsing



public class JSON2Apex 

public class User
public String name get;set;
public String twitter get;set;

public User(JSONParser parser)
while (parser.nextToken() != System.JSONToken.END_OBJECT)
if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME)
String text = parser.getText();
if (parser.nextToken() != System.JSONToken.VALUE_NULL)
if (text == 'name')
name = parser.getText();
else if (text == 'twitter')
twitter = parser.getText();
else
System.debug(LoggingLevel.WARN, 'User consuming unrecognized property: '+text);
consumeObject(parser);







public User user get;set;

public JSON2Apex(JSONParser parser)
while (parser.nextToken() != System.JSONToken.END_OBJECT)
if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME)
String text = parser.getText();
if (parser.nextToken() != System.JSONToken.VALUE_NULL)
if (text == 'user')
user = new User(parser);
else
System.debug(LoggingLevel.WARN, 'JSON2Apex consuming unrecognized property: '+text);
consumeObject(parser);







public static JSON2Apex parse(String json)
System.JSONParser parser = System.JSON.createParser(json);
return new JSON2Apex(parser);


public static void consumeObject(System.JSONParser parser)
Integer depth = 0;
do
curr == System.JSONToken.START_ARRAY)
depth++;
else if (curr == System.JSONToken.END_OBJECT while (depth > 0 && parser.nextToken() != null);








JSON.deserialize



public class JSON2Apex 

public class User
public String name;
public String twitter;


public User user;


public static JSON2Apex parse(String json)
return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);











share|improve this question




























    1















    The JSON2Apex web tool offers 2 methods of parsing of the JSON string: one uses JSON.deserialize method, and the other creates parser and iterates over the input json. The second option can be enabled by checking "Create explicit parse code" in the tool.



    QUESTION



    In what cases would a developer prefer explicit parsing to a simple JSON.deserialize? If we compare both options the later seems to be much clear and less verbose which makes code more readable.



    Explicit parsing



    public class JSON2Apex 

    public class User
    public String name get;set;
    public String twitter get;set;

    public User(JSONParser parser)
    while (parser.nextToken() != System.JSONToken.END_OBJECT)
    if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME)
    String text = parser.getText();
    if (parser.nextToken() != System.JSONToken.VALUE_NULL)
    if (text == 'name')
    name = parser.getText();
    else if (text == 'twitter')
    twitter = parser.getText();
    else
    System.debug(LoggingLevel.WARN, 'User consuming unrecognized property: '+text);
    consumeObject(parser);







    public User user get;set;

    public JSON2Apex(JSONParser parser)
    while (parser.nextToken() != System.JSONToken.END_OBJECT)
    if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME)
    String text = parser.getText();
    if (parser.nextToken() != System.JSONToken.VALUE_NULL)
    if (text == 'user')
    user = new User(parser);
    else
    System.debug(LoggingLevel.WARN, 'JSON2Apex consuming unrecognized property: '+text);
    consumeObject(parser);







    public static JSON2Apex parse(String json)
    System.JSONParser parser = System.JSON.createParser(json);
    return new JSON2Apex(parser);


    public static void consumeObject(System.JSONParser parser)
    Integer depth = 0;
    do
    curr == System.JSONToken.START_ARRAY)
    depth++;
    else if (curr == System.JSONToken.END_OBJECT while (depth > 0 && parser.nextToken() != null);








    JSON.deserialize



    public class JSON2Apex 

    public class User
    public String name;
    public String twitter;


    public User user;


    public static JSON2Apex parse(String json)
    return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);











    share|improve this question
























      1












      1








      1








      The JSON2Apex web tool offers 2 methods of parsing of the JSON string: one uses JSON.deserialize method, and the other creates parser and iterates over the input json. The second option can be enabled by checking "Create explicit parse code" in the tool.



      QUESTION



      In what cases would a developer prefer explicit parsing to a simple JSON.deserialize? If we compare both options the later seems to be much clear and less verbose which makes code more readable.



      Explicit parsing



      public class JSON2Apex 

      public class User
      public String name get;set;
      public String twitter get;set;

      public User(JSONParser parser)
      while (parser.nextToken() != System.JSONToken.END_OBJECT)
      if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME)
      String text = parser.getText();
      if (parser.nextToken() != System.JSONToken.VALUE_NULL)
      if (text == 'name')
      name = parser.getText();
      else if (text == 'twitter')
      twitter = parser.getText();
      else
      System.debug(LoggingLevel.WARN, 'User consuming unrecognized property: '+text);
      consumeObject(parser);







      public User user get;set;

      public JSON2Apex(JSONParser parser)
      while (parser.nextToken() != System.JSONToken.END_OBJECT)
      if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME)
      String text = parser.getText();
      if (parser.nextToken() != System.JSONToken.VALUE_NULL)
      if (text == 'user')
      user = new User(parser);
      else
      System.debug(LoggingLevel.WARN, 'JSON2Apex consuming unrecognized property: '+text);
      consumeObject(parser);







      public static JSON2Apex parse(String json)
      System.JSONParser parser = System.JSON.createParser(json);
      return new JSON2Apex(parser);


      public static void consumeObject(System.JSONParser parser)
      Integer depth = 0;
      do
      curr == System.JSONToken.START_ARRAY)
      depth++;
      else if (curr == System.JSONToken.END_OBJECT while (depth > 0 && parser.nextToken() != null);








      JSON.deserialize



      public class JSON2Apex 

      public class User
      public String name;
      public String twitter;


      public User user;


      public static JSON2Apex parse(String json)
      return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);











      share|improve this question














      The JSON2Apex web tool offers 2 methods of parsing of the JSON string: one uses JSON.deserialize method, and the other creates parser and iterates over the input json. The second option can be enabled by checking "Create explicit parse code" in the tool.



      QUESTION



      In what cases would a developer prefer explicit parsing to a simple JSON.deserialize? If we compare both options the later seems to be much clear and less verbose which makes code more readable.



      Explicit parsing



      public class JSON2Apex 

      public class User
      public String name get;set;
      public String twitter get;set;

      public User(JSONParser parser)
      while (parser.nextToken() != System.JSONToken.END_OBJECT)
      if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME)
      String text = parser.getText();
      if (parser.nextToken() != System.JSONToken.VALUE_NULL)
      if (text == 'name')
      name = parser.getText();
      else if (text == 'twitter')
      twitter = parser.getText();
      else
      System.debug(LoggingLevel.WARN, 'User consuming unrecognized property: '+text);
      consumeObject(parser);







      public User user get;set;

      public JSON2Apex(JSONParser parser)
      while (parser.nextToken() != System.JSONToken.END_OBJECT)
      if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME)
      String text = parser.getText();
      if (parser.nextToken() != System.JSONToken.VALUE_NULL)
      if (text == 'user')
      user = new User(parser);
      else
      System.debug(LoggingLevel.WARN, 'JSON2Apex consuming unrecognized property: '+text);
      consumeObject(parser);







      public static JSON2Apex parse(String json)
      System.JSONParser parser = System.JSON.createParser(json);
      return new JSON2Apex(parser);


      public static void consumeObject(System.JSONParser parser)
      Integer depth = 0;
      do
      curr == System.JSONToken.START_ARRAY)
      depth++;
      else if (curr == System.JSONToken.END_OBJECT while (depth > 0 && parser.nextToken() != null);








      JSON.deserialize



      public class JSON2Apex 

      public class User
      public String name;
      public String twitter;


      public User user;


      public static JSON2Apex parse(String json)
      return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);








      json parsing






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Apr 9 at 7:20









      EduardEduard

      1,9022723




      1,9022723




















          1 Answer
          1






          active

          oldest

          votes


















          4














          Apex code has reserved names (keywords) and special variable rules (e.g. cannot start with a number, can't have __, etc) that you can't use in JSON objects. You don't want to use explicit mode if you can help it, because it has worse performance compared to JSON.deserialize, but it gets around compilation errors if you have a JSON string like:



           "title": "Writing JSON", "abstract": "A short document about how to use JSON." 


          This would compile to:



          public class JSON2Apex 
          public String title;
          public String abstract;



          But abstract is a reserved keyword. You can't deploy this code to Salesforce. By changing the code:



          public class JSON2Apex 
          public String title;
          public String abstract_x;



          The code can then compile, but you need explicit parsing in order to translate abstract in the JSON string to abstract_x in Apex.






          share|improve this answer























          • Thanks for your prompt answer! If this is the only reason why a developer would use explicit parsing, then I would definitely go with deserialize all the time. It's possible to keep a Map of reserved words and their substitutes, and perform replace in the input json string before parsing. This is exaclty how the ffhttp_JsonDeserializer.cls class works.

            – Eduard
            Apr 9 at 7:56






          • 1





            @Eduard Yes, there are better ways. JSON2Apex is a rather old utility, useful in most cases, but explicit mode wasn't the best idea. There's definitely better ways to do it.

            – sfdcfox
            Apr 9 at 7:59











          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "459"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f257118%2fexplicitly-parse-json-string-vs-json-deserialize%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4














          Apex code has reserved names (keywords) and special variable rules (e.g. cannot start with a number, can't have __, etc) that you can't use in JSON objects. You don't want to use explicit mode if you can help it, because it has worse performance compared to JSON.deserialize, but it gets around compilation errors if you have a JSON string like:



           "title": "Writing JSON", "abstract": "A short document about how to use JSON." 


          This would compile to:



          public class JSON2Apex 
          public String title;
          public String abstract;



          But abstract is a reserved keyword. You can't deploy this code to Salesforce. By changing the code:



          public class JSON2Apex 
          public String title;
          public String abstract_x;



          The code can then compile, but you need explicit parsing in order to translate abstract in the JSON string to abstract_x in Apex.






          share|improve this answer























          • Thanks for your prompt answer! If this is the only reason why a developer would use explicit parsing, then I would definitely go with deserialize all the time. It's possible to keep a Map of reserved words and their substitutes, and perform replace in the input json string before parsing. This is exaclty how the ffhttp_JsonDeserializer.cls class works.

            – Eduard
            Apr 9 at 7:56






          • 1





            @Eduard Yes, there are better ways. JSON2Apex is a rather old utility, useful in most cases, but explicit mode wasn't the best idea. There's definitely better ways to do it.

            – sfdcfox
            Apr 9 at 7:59















          4














          Apex code has reserved names (keywords) and special variable rules (e.g. cannot start with a number, can't have __, etc) that you can't use in JSON objects. You don't want to use explicit mode if you can help it, because it has worse performance compared to JSON.deserialize, but it gets around compilation errors if you have a JSON string like:



           "title": "Writing JSON", "abstract": "A short document about how to use JSON." 


          This would compile to:



          public class JSON2Apex 
          public String title;
          public String abstract;



          But abstract is a reserved keyword. You can't deploy this code to Salesforce. By changing the code:



          public class JSON2Apex 
          public String title;
          public String abstract_x;



          The code can then compile, but you need explicit parsing in order to translate abstract in the JSON string to abstract_x in Apex.






          share|improve this answer























          • Thanks for your prompt answer! If this is the only reason why a developer would use explicit parsing, then I would definitely go with deserialize all the time. It's possible to keep a Map of reserved words and their substitutes, and perform replace in the input json string before parsing. This is exaclty how the ffhttp_JsonDeserializer.cls class works.

            – Eduard
            Apr 9 at 7:56






          • 1





            @Eduard Yes, there are better ways. JSON2Apex is a rather old utility, useful in most cases, but explicit mode wasn't the best idea. There's definitely better ways to do it.

            – sfdcfox
            Apr 9 at 7:59













          4












          4








          4







          Apex code has reserved names (keywords) and special variable rules (e.g. cannot start with a number, can't have __, etc) that you can't use in JSON objects. You don't want to use explicit mode if you can help it, because it has worse performance compared to JSON.deserialize, but it gets around compilation errors if you have a JSON string like:



           "title": "Writing JSON", "abstract": "A short document about how to use JSON." 


          This would compile to:



          public class JSON2Apex 
          public String title;
          public String abstract;



          But abstract is a reserved keyword. You can't deploy this code to Salesforce. By changing the code:



          public class JSON2Apex 
          public String title;
          public String abstract_x;



          The code can then compile, but you need explicit parsing in order to translate abstract in the JSON string to abstract_x in Apex.






          share|improve this answer













          Apex code has reserved names (keywords) and special variable rules (e.g. cannot start with a number, can't have __, etc) that you can't use in JSON objects. You don't want to use explicit mode if you can help it, because it has worse performance compared to JSON.deserialize, but it gets around compilation errors if you have a JSON string like:



           "title": "Writing JSON", "abstract": "A short document about how to use JSON." 


          This would compile to:



          public class JSON2Apex 
          public String title;
          public String abstract;



          But abstract is a reserved keyword. You can't deploy this code to Salesforce. By changing the code:



          public class JSON2Apex 
          public String title;
          public String abstract_x;



          The code can then compile, but you need explicit parsing in order to translate abstract in the JSON string to abstract_x in Apex.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Apr 9 at 7:38









          sfdcfoxsfdcfox

          265k13211458




          265k13211458












          • Thanks for your prompt answer! If this is the only reason why a developer would use explicit parsing, then I would definitely go with deserialize all the time. It's possible to keep a Map of reserved words and their substitutes, and perform replace in the input json string before parsing. This is exaclty how the ffhttp_JsonDeserializer.cls class works.

            – Eduard
            Apr 9 at 7:56






          • 1





            @Eduard Yes, there are better ways. JSON2Apex is a rather old utility, useful in most cases, but explicit mode wasn't the best idea. There's definitely better ways to do it.

            – sfdcfox
            Apr 9 at 7:59

















          • Thanks for your prompt answer! If this is the only reason why a developer would use explicit parsing, then I would definitely go with deserialize all the time. It's possible to keep a Map of reserved words and their substitutes, and perform replace in the input json string before parsing. This is exaclty how the ffhttp_JsonDeserializer.cls class works.

            – Eduard
            Apr 9 at 7:56






          • 1





            @Eduard Yes, there are better ways. JSON2Apex is a rather old utility, useful in most cases, but explicit mode wasn't the best idea. There's definitely better ways to do it.

            – sfdcfox
            Apr 9 at 7:59
















          Thanks for your prompt answer! If this is the only reason why a developer would use explicit parsing, then I would definitely go with deserialize all the time. It's possible to keep a Map of reserved words and their substitutes, and perform replace in the input json string before parsing. This is exaclty how the ffhttp_JsonDeserializer.cls class works.

          – Eduard
          Apr 9 at 7:56





          Thanks for your prompt answer! If this is the only reason why a developer would use explicit parsing, then I would definitely go with deserialize all the time. It's possible to keep a Map of reserved words and their substitutes, and perform replace in the input json string before parsing. This is exaclty how the ffhttp_JsonDeserializer.cls class works.

          – Eduard
          Apr 9 at 7:56




          1




          1





          @Eduard Yes, there are better ways. JSON2Apex is a rather old utility, useful in most cases, but explicit mode wasn't the best idea. There's definitely better ways to do it.

          – sfdcfox
          Apr 9 at 7:59





          @Eduard Yes, there are better ways. JSON2Apex is a rather old utility, useful in most cases, but explicit mode wasn't the best idea. There's definitely better ways to do it.

          – sfdcfox
          Apr 9 at 7:59

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Salesforce Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f257118%2fexplicitly-parse-json-string-vs-json-deserialize%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

          Bruxelas-Capital Índice Historia | Composición | Situación lingüística | Clima | Cidades irmandadas | Notas | Véxase tamén | Menú de navegacióneO uso das linguas en Bruxelas e a situación do neerlandés"Rexión de Bruxelas Capital"o orixinalSitio da rexiónPáxina de Bruselas no sitio da Oficina de Promoción Turística de Valonia e BruxelasMapa Interactivo da Rexión de Bruxelas-CapitaleeWorldCat332144929079854441105155190212ID28008674080552-90000 0001 0666 3698n94104302ID540940339365017018237

          What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company