How to create a recursive method in Apex which takes a dot notation string and convert it into Hierarchical...











up vote
7
down vote

favorite
1












I'm trying to create a utility class/method where a certain method will accept a list of Strings - each string will be constructed as follows:



"Root.Parent.Child... N"


This string can be N long (or basically holds infinite number of parts).



Each Part of the String (parts are the split string by dot) is intended to be a Json Object.



For Example:



  //sample data
String rec1 = 'Root.Parent.FirstChild';
String rec2 = 'Root.Parent.FirstChild2';
String rec3 = 'Root.Parent2.Child';
String rec4 = 'Root.Parent2.Child2';
String fullPathsList = new List<String>{ rec1,rec2,rec3,rec4 };

//should create as many maps as needed dynamically based on total size of string paths
Map<String,Object> output = new Map<String,Object>();
Map<String,Object> root = new Map<String,Object>();
Map<String,Object> level1 = new Map<String,Object>();
Map<String,Object> level2 = new Map<String,Object>();

//iterate over the full list and grab each path
for(String fullJsonPath:fullPathsList ) {
//check if has a dot
if( fullJsonPath.indexOf('.') != -1 ){
String pathPartsList = fullJsonPath.split('\.');
Integer totalSize = pathPartsList.size();
for(Integer i=0;i<totalSize;i++) {
level2.put(pathPartsList[totalSize-1] , 'VALUE');
if(totalSize-2 > 0){
level1.put(pathPartsList[totalSize-2], level2);
}
root.put(pathPartsList[0], level1);
}
}
output.put('results', root);
}

System.debug('@@@ output ' + JSON.serialize(output));


The output will show :



{ "results": {
"Root": {
"Parent2": {
"Child2": "VALUE",
"Child": "VALUE",
"FirstChild2": "VALUE",
"FirstChild": "VALUE"
},
"Parent": {
"Child2": "VALUE",
"Child": "VALUE",
"FirstChild2": "VALUE",
"FirstChild": "VALUE"
}
}
}
}


My problems here is :




  1. The level 2 map is holding all childs - each parent holds all childs
    and not only it's own.

  2. I need to have an ability to generate those Maps dynamically based on the number of childs the strings have - was thinking some
    kind of a recursion method will do the trick.


Anybody see a clever way of achieving this in Apex?



In Javascript it's pretty simple with this one liner which I'm trying to replicate somehow in Apex (any equivalent reduce method?) :



'Root.Parent.FirstChild'.split('.').reduce((o,i)=>o[i], obj);









share|improve this question


























    up vote
    7
    down vote

    favorite
    1












    I'm trying to create a utility class/method where a certain method will accept a list of Strings - each string will be constructed as follows:



    "Root.Parent.Child... N"


    This string can be N long (or basically holds infinite number of parts).



    Each Part of the String (parts are the split string by dot) is intended to be a Json Object.



    For Example:



      //sample data
    String rec1 = 'Root.Parent.FirstChild';
    String rec2 = 'Root.Parent.FirstChild2';
    String rec3 = 'Root.Parent2.Child';
    String rec4 = 'Root.Parent2.Child2';
    String fullPathsList = new List<String>{ rec1,rec2,rec3,rec4 };

    //should create as many maps as needed dynamically based on total size of string paths
    Map<String,Object> output = new Map<String,Object>();
    Map<String,Object> root = new Map<String,Object>();
    Map<String,Object> level1 = new Map<String,Object>();
    Map<String,Object> level2 = new Map<String,Object>();

    //iterate over the full list and grab each path
    for(String fullJsonPath:fullPathsList ) {
    //check if has a dot
    if( fullJsonPath.indexOf('.') != -1 ){
    String pathPartsList = fullJsonPath.split('\.');
    Integer totalSize = pathPartsList.size();
    for(Integer i=0;i<totalSize;i++) {
    level2.put(pathPartsList[totalSize-1] , 'VALUE');
    if(totalSize-2 > 0){
    level1.put(pathPartsList[totalSize-2], level2);
    }
    root.put(pathPartsList[0], level1);
    }
    }
    output.put('results', root);
    }

    System.debug('@@@ output ' + JSON.serialize(output));


    The output will show :



    { "results": {
    "Root": {
    "Parent2": {
    "Child2": "VALUE",
    "Child": "VALUE",
    "FirstChild2": "VALUE",
    "FirstChild": "VALUE"
    },
    "Parent": {
    "Child2": "VALUE",
    "Child": "VALUE",
    "FirstChild2": "VALUE",
    "FirstChild": "VALUE"
    }
    }
    }
    }


    My problems here is :




    1. The level 2 map is holding all childs - each parent holds all childs
      and not only it's own.

    2. I need to have an ability to generate those Maps dynamically based on the number of childs the strings have - was thinking some
      kind of a recursion method will do the trick.


    Anybody see a clever way of achieving this in Apex?



    In Javascript it's pretty simple with this one liner which I'm trying to replicate somehow in Apex (any equivalent reduce method?) :



    'Root.Parent.FirstChild'.split('.').reduce((o,i)=>o[i], obj);









    share|improve this question
























      up vote
      7
      down vote

      favorite
      1









      up vote
      7
      down vote

      favorite
      1






      1





      I'm trying to create a utility class/method where a certain method will accept a list of Strings - each string will be constructed as follows:



      "Root.Parent.Child... N"


      This string can be N long (or basically holds infinite number of parts).



      Each Part of the String (parts are the split string by dot) is intended to be a Json Object.



      For Example:



        //sample data
      String rec1 = 'Root.Parent.FirstChild';
      String rec2 = 'Root.Parent.FirstChild2';
      String rec3 = 'Root.Parent2.Child';
      String rec4 = 'Root.Parent2.Child2';
      String fullPathsList = new List<String>{ rec1,rec2,rec3,rec4 };

      //should create as many maps as needed dynamically based on total size of string paths
      Map<String,Object> output = new Map<String,Object>();
      Map<String,Object> root = new Map<String,Object>();
      Map<String,Object> level1 = new Map<String,Object>();
      Map<String,Object> level2 = new Map<String,Object>();

      //iterate over the full list and grab each path
      for(String fullJsonPath:fullPathsList ) {
      //check if has a dot
      if( fullJsonPath.indexOf('.') != -1 ){
      String pathPartsList = fullJsonPath.split('\.');
      Integer totalSize = pathPartsList.size();
      for(Integer i=0;i<totalSize;i++) {
      level2.put(pathPartsList[totalSize-1] , 'VALUE');
      if(totalSize-2 > 0){
      level1.put(pathPartsList[totalSize-2], level2);
      }
      root.put(pathPartsList[0], level1);
      }
      }
      output.put('results', root);
      }

      System.debug('@@@ output ' + JSON.serialize(output));


      The output will show :



      { "results": {
      "Root": {
      "Parent2": {
      "Child2": "VALUE",
      "Child": "VALUE",
      "FirstChild2": "VALUE",
      "FirstChild": "VALUE"
      },
      "Parent": {
      "Child2": "VALUE",
      "Child": "VALUE",
      "FirstChild2": "VALUE",
      "FirstChild": "VALUE"
      }
      }
      }
      }


      My problems here is :




      1. The level 2 map is holding all childs - each parent holds all childs
        and not only it's own.

      2. I need to have an ability to generate those Maps dynamically based on the number of childs the strings have - was thinking some
        kind of a recursion method will do the trick.


      Anybody see a clever way of achieving this in Apex?



      In Javascript it's pretty simple with this one liner which I'm trying to replicate somehow in Apex (any equivalent reduce method?) :



      'Root.Parent.FirstChild'.split('.').reduce((o,i)=>o[i], obj);









      share|improve this question













      I'm trying to create a utility class/method where a certain method will accept a list of Strings - each string will be constructed as follows:



      "Root.Parent.Child... N"


      This string can be N long (or basically holds infinite number of parts).



      Each Part of the String (parts are the split string by dot) is intended to be a Json Object.



      For Example:



        //sample data
      String rec1 = 'Root.Parent.FirstChild';
      String rec2 = 'Root.Parent.FirstChild2';
      String rec3 = 'Root.Parent2.Child';
      String rec4 = 'Root.Parent2.Child2';
      String fullPathsList = new List<String>{ rec1,rec2,rec3,rec4 };

      //should create as many maps as needed dynamically based on total size of string paths
      Map<String,Object> output = new Map<String,Object>();
      Map<String,Object> root = new Map<String,Object>();
      Map<String,Object> level1 = new Map<String,Object>();
      Map<String,Object> level2 = new Map<String,Object>();

      //iterate over the full list and grab each path
      for(String fullJsonPath:fullPathsList ) {
      //check if has a dot
      if( fullJsonPath.indexOf('.') != -1 ){
      String pathPartsList = fullJsonPath.split('\.');
      Integer totalSize = pathPartsList.size();
      for(Integer i=0;i<totalSize;i++) {
      level2.put(pathPartsList[totalSize-1] , 'VALUE');
      if(totalSize-2 > 0){
      level1.put(pathPartsList[totalSize-2], level2);
      }
      root.put(pathPartsList[0], level1);
      }
      }
      output.put('results', root);
      }

      System.debug('@@@ output ' + JSON.serialize(output));


      The output will show :



      { "results": {
      "Root": {
      "Parent2": {
      "Child2": "VALUE",
      "Child": "VALUE",
      "FirstChild2": "VALUE",
      "FirstChild": "VALUE"
      },
      "Parent": {
      "Child2": "VALUE",
      "Child": "VALUE",
      "FirstChild2": "VALUE",
      "FirstChild": "VALUE"
      }
      }
      }
      }


      My problems here is :




      1. The level 2 map is holding all childs - each parent holds all childs
        and not only it's own.

      2. I need to have an ability to generate those Maps dynamically based on the number of childs the strings have - was thinking some
        kind of a recursion method will do the trick.


      Anybody see a clever way of achieving this in Apex?



      In Javascript it's pretty simple with this one liner which I'm trying to replicate somehow in Apex (any equivalent reduce method?) :



      'Root.Parent.FirstChild'.split('.').reduce((o,i)=>o[i], obj);






      apex json






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 30 at 11:58









      sfdx bomb

      640614




      640614






















          3 Answers
          3






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted










          I've done exactly this before. Here's working code for it:



          public class JsonBoxer {

          public Map<String, Object> root {get; private set;}

          public JsonBoxer() {
          this.root = new Map<String, Object>();
          }

          public void put(String key, Object value) {
          doPut(root, key.split('\.'), value);
          }

          private void doPut(Map<String, Object> currentRoot, List<String> keyChain, Object value) {
          if(keyChain.size() == 1) {
          currentRoot.put(keyChain[0], value);
          } else {
          String thisKey = keyChain.remove(0);
          Map<String, Object> child = (Map<String, Object>)currentRoot.get(thisKey);
          if(child == null) {
          child = new Map<String, Object>();
          currentRoot.put(thisKey, child);
          }

          doPut(child, keyChain, value);
          }
          }
          }


          Even with a test:



          @IsTest
          private class JsonBoxerTest {

          @IsTest static void noBoxing() {
          JsonBoxer boxer = new JsonBoxer();

          boxer.put('a', 'b');

          System.assertEquals('b', boxer.root.get('a'));
          }

          @IsTest static void boxing() {
          JsonBoxer boxer = new JsonBoxer();

          boxer.put('a.1', 'b');

          System.assertEquals('b', ((Map<String, Object>)boxer.root.get('a')).get('1'));
          }

          @IsTest static void twoSubKeyValues() {
          JsonBoxer boxer = new JsonBoxer();

          boxer.put('a.1', 'b');
          boxer.put('a.2', 'c');

          System.assertEquals('b', ((Map<String, Object>)boxer.root.get('a')).get('1'));
          System.assertEquals('c', ((Map<String, Object>)boxer.root.get('a')).get('2'));
          }

          @IsTest static void overwriteSubKey() {
          JsonBoxer boxer = new JsonBoxer();

          boxer.put('a.1', 'b');
          boxer.put('a.1', 'c');

          System.assertEquals('c', ((Map<String, Object>)boxer.root.get('a')).get('1'));
          }
          }





          share|improve this answer




























            up vote
            4
            down vote













            Something like This probably



            public with sharing class MyClass {

            public static Map<String, Object> get(String input) {

            if (input == null) return null;
            if (!input.contains('.')) return new Map<String, Object>{input => null};

            return new Map<String, Object>{
            input.substringBefore('.') => get(input.substringAfter('.'))
            };

            }
            }


            Then executing:



            System.debug(JSON.serialize(MyClass.get('Root.Parent.FirstChild')));


            Output : {"Root":{"Parent":{"FirstChild":null}}






            share|improve this answer




























              up vote
              3
              down vote













              One of the approaches would be create a inner wrapper class for Map, and define own method to set value based on path.



              Most of the code is already written in your question, so check the following pseudo-code:



              public class SuperMap {
              Map<String, Object> ResultMap;

              public SuperMap() {
              ResultMap = new Map<String, Object>();
              }

              public void specifyValue(String path, Object value) {
              Map<String, Object> current_map = ResultMap;
              List<String> path_steps = path.split('\.');
              for(Integer i = 0; i < path_steps.size() - 1; i++) {
              String step = path_steps.get(i);
              if (!current_map.containsKey(step)) {
              current_map.put(step, (Object)new Map<String, Object>());
              }
              current_map = (Map<String, Object>)current_map.get(step);
              }
              current_map.put(path_steps.get(path_steps.size() - 1), value);
              }
              public String returnString() {
              return JSON.serialize(ResultMap);
              }
              }


              Example of usage:



              SuperMap mp = new SuperMap();
              mp.specifyValue('kuru.123.dev','Data');
              mp.specifyValue('grey.123.dev2','Data2');
              mp.specifyValue('grey.123.dev2','Data3');
              System.debug(mp.returnString());





              share|improve this answer





















                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',
                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%2f241048%2fhow-to-create-a-recursive-method-in-apex-which-takes-a-dot-notation-string-and-c%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                3
                down vote



                accepted










                I've done exactly this before. Here's working code for it:



                public class JsonBoxer {

                public Map<String, Object> root {get; private set;}

                public JsonBoxer() {
                this.root = new Map<String, Object>();
                }

                public void put(String key, Object value) {
                doPut(root, key.split('\.'), value);
                }

                private void doPut(Map<String, Object> currentRoot, List<String> keyChain, Object value) {
                if(keyChain.size() == 1) {
                currentRoot.put(keyChain[0], value);
                } else {
                String thisKey = keyChain.remove(0);
                Map<String, Object> child = (Map<String, Object>)currentRoot.get(thisKey);
                if(child == null) {
                child = new Map<String, Object>();
                currentRoot.put(thisKey, child);
                }

                doPut(child, keyChain, value);
                }
                }
                }


                Even with a test:



                @IsTest
                private class JsonBoxerTest {

                @IsTest static void noBoxing() {
                JsonBoxer boxer = new JsonBoxer();

                boxer.put('a', 'b');

                System.assertEquals('b', boxer.root.get('a'));
                }

                @IsTest static void boxing() {
                JsonBoxer boxer = new JsonBoxer();

                boxer.put('a.1', 'b');

                System.assertEquals('b', ((Map<String, Object>)boxer.root.get('a')).get('1'));
                }

                @IsTest static void twoSubKeyValues() {
                JsonBoxer boxer = new JsonBoxer();

                boxer.put('a.1', 'b');
                boxer.put('a.2', 'c');

                System.assertEquals('b', ((Map<String, Object>)boxer.root.get('a')).get('1'));
                System.assertEquals('c', ((Map<String, Object>)boxer.root.get('a')).get('2'));
                }

                @IsTest static void overwriteSubKey() {
                JsonBoxer boxer = new JsonBoxer();

                boxer.put('a.1', 'b');
                boxer.put('a.1', 'c');

                System.assertEquals('c', ((Map<String, Object>)boxer.root.get('a')).get('1'));
                }
                }





                share|improve this answer

























                  up vote
                  3
                  down vote



                  accepted










                  I've done exactly this before. Here's working code for it:



                  public class JsonBoxer {

                  public Map<String, Object> root {get; private set;}

                  public JsonBoxer() {
                  this.root = new Map<String, Object>();
                  }

                  public void put(String key, Object value) {
                  doPut(root, key.split('\.'), value);
                  }

                  private void doPut(Map<String, Object> currentRoot, List<String> keyChain, Object value) {
                  if(keyChain.size() == 1) {
                  currentRoot.put(keyChain[0], value);
                  } else {
                  String thisKey = keyChain.remove(0);
                  Map<String, Object> child = (Map<String, Object>)currentRoot.get(thisKey);
                  if(child == null) {
                  child = new Map<String, Object>();
                  currentRoot.put(thisKey, child);
                  }

                  doPut(child, keyChain, value);
                  }
                  }
                  }


                  Even with a test:



                  @IsTest
                  private class JsonBoxerTest {

                  @IsTest static void noBoxing() {
                  JsonBoxer boxer = new JsonBoxer();

                  boxer.put('a', 'b');

                  System.assertEquals('b', boxer.root.get('a'));
                  }

                  @IsTest static void boxing() {
                  JsonBoxer boxer = new JsonBoxer();

                  boxer.put('a.1', 'b');

                  System.assertEquals('b', ((Map<String, Object>)boxer.root.get('a')).get('1'));
                  }

                  @IsTest static void twoSubKeyValues() {
                  JsonBoxer boxer = new JsonBoxer();

                  boxer.put('a.1', 'b');
                  boxer.put('a.2', 'c');

                  System.assertEquals('b', ((Map<String, Object>)boxer.root.get('a')).get('1'));
                  System.assertEquals('c', ((Map<String, Object>)boxer.root.get('a')).get('2'));
                  }

                  @IsTest static void overwriteSubKey() {
                  JsonBoxer boxer = new JsonBoxer();

                  boxer.put('a.1', 'b');
                  boxer.put('a.1', 'c');

                  System.assertEquals('c', ((Map<String, Object>)boxer.root.get('a')).get('1'));
                  }
                  }





                  share|improve this answer























                    up vote
                    3
                    down vote



                    accepted







                    up vote
                    3
                    down vote



                    accepted






                    I've done exactly this before. Here's working code for it:



                    public class JsonBoxer {

                    public Map<String, Object> root {get; private set;}

                    public JsonBoxer() {
                    this.root = new Map<String, Object>();
                    }

                    public void put(String key, Object value) {
                    doPut(root, key.split('\.'), value);
                    }

                    private void doPut(Map<String, Object> currentRoot, List<String> keyChain, Object value) {
                    if(keyChain.size() == 1) {
                    currentRoot.put(keyChain[0], value);
                    } else {
                    String thisKey = keyChain.remove(0);
                    Map<String, Object> child = (Map<String, Object>)currentRoot.get(thisKey);
                    if(child == null) {
                    child = new Map<String, Object>();
                    currentRoot.put(thisKey, child);
                    }

                    doPut(child, keyChain, value);
                    }
                    }
                    }


                    Even with a test:



                    @IsTest
                    private class JsonBoxerTest {

                    @IsTest static void noBoxing() {
                    JsonBoxer boxer = new JsonBoxer();

                    boxer.put('a', 'b');

                    System.assertEquals('b', boxer.root.get('a'));
                    }

                    @IsTest static void boxing() {
                    JsonBoxer boxer = new JsonBoxer();

                    boxer.put('a.1', 'b');

                    System.assertEquals('b', ((Map<String, Object>)boxer.root.get('a')).get('1'));
                    }

                    @IsTest static void twoSubKeyValues() {
                    JsonBoxer boxer = new JsonBoxer();

                    boxer.put('a.1', 'b');
                    boxer.put('a.2', 'c');

                    System.assertEquals('b', ((Map<String, Object>)boxer.root.get('a')).get('1'));
                    System.assertEquals('c', ((Map<String, Object>)boxer.root.get('a')).get('2'));
                    }

                    @IsTest static void overwriteSubKey() {
                    JsonBoxer boxer = new JsonBoxer();

                    boxer.put('a.1', 'b');
                    boxer.put('a.1', 'c');

                    System.assertEquals('c', ((Map<String, Object>)boxer.root.get('a')).get('1'));
                    }
                    }





                    share|improve this answer












                    I've done exactly this before. Here's working code for it:



                    public class JsonBoxer {

                    public Map<String, Object> root {get; private set;}

                    public JsonBoxer() {
                    this.root = new Map<String, Object>();
                    }

                    public void put(String key, Object value) {
                    doPut(root, key.split('\.'), value);
                    }

                    private void doPut(Map<String, Object> currentRoot, List<String> keyChain, Object value) {
                    if(keyChain.size() == 1) {
                    currentRoot.put(keyChain[0], value);
                    } else {
                    String thisKey = keyChain.remove(0);
                    Map<String, Object> child = (Map<String, Object>)currentRoot.get(thisKey);
                    if(child == null) {
                    child = new Map<String, Object>();
                    currentRoot.put(thisKey, child);
                    }

                    doPut(child, keyChain, value);
                    }
                    }
                    }


                    Even with a test:



                    @IsTest
                    private class JsonBoxerTest {

                    @IsTest static void noBoxing() {
                    JsonBoxer boxer = new JsonBoxer();

                    boxer.put('a', 'b');

                    System.assertEquals('b', boxer.root.get('a'));
                    }

                    @IsTest static void boxing() {
                    JsonBoxer boxer = new JsonBoxer();

                    boxer.put('a.1', 'b');

                    System.assertEquals('b', ((Map<String, Object>)boxer.root.get('a')).get('1'));
                    }

                    @IsTest static void twoSubKeyValues() {
                    JsonBoxer boxer = new JsonBoxer();

                    boxer.put('a.1', 'b');
                    boxer.put('a.2', 'c');

                    System.assertEquals('b', ((Map<String, Object>)boxer.root.get('a')).get('1'));
                    System.assertEquals('c', ((Map<String, Object>)boxer.root.get('a')).get('2'));
                    }

                    @IsTest static void overwriteSubKey() {
                    JsonBoxer boxer = new JsonBoxer();

                    boxer.put('a.1', 'b');
                    boxer.put('a.1', 'c');

                    System.assertEquals('c', ((Map<String, Object>)boxer.root.get('a')).get('1'));
                    }
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 30 at 15:36









                    Aidan

                    6,725942




                    6,725942
























                        up vote
                        4
                        down vote













                        Something like This probably



                        public with sharing class MyClass {

                        public static Map<String, Object> get(String input) {

                        if (input == null) return null;
                        if (!input.contains('.')) return new Map<String, Object>{input => null};

                        return new Map<String, Object>{
                        input.substringBefore('.') => get(input.substringAfter('.'))
                        };

                        }
                        }


                        Then executing:



                        System.debug(JSON.serialize(MyClass.get('Root.Parent.FirstChild')));


                        Output : {"Root":{"Parent":{"FirstChild":null}}






                        share|improve this answer

























                          up vote
                          4
                          down vote













                          Something like This probably



                          public with sharing class MyClass {

                          public static Map<String, Object> get(String input) {

                          if (input == null) return null;
                          if (!input.contains('.')) return new Map<String, Object>{input => null};

                          return new Map<String, Object>{
                          input.substringBefore('.') => get(input.substringAfter('.'))
                          };

                          }
                          }


                          Then executing:



                          System.debug(JSON.serialize(MyClass.get('Root.Parent.FirstChild')));


                          Output : {"Root":{"Parent":{"FirstChild":null}}






                          share|improve this answer























                            up vote
                            4
                            down vote










                            up vote
                            4
                            down vote









                            Something like This probably



                            public with sharing class MyClass {

                            public static Map<String, Object> get(String input) {

                            if (input == null) return null;
                            if (!input.contains('.')) return new Map<String, Object>{input => null};

                            return new Map<String, Object>{
                            input.substringBefore('.') => get(input.substringAfter('.'))
                            };

                            }
                            }


                            Then executing:



                            System.debug(JSON.serialize(MyClass.get('Root.Parent.FirstChild')));


                            Output : {"Root":{"Parent":{"FirstChild":null}}






                            share|improve this answer












                            Something like This probably



                            public with sharing class MyClass {

                            public static Map<String, Object> get(String input) {

                            if (input == null) return null;
                            if (!input.contains('.')) return new Map<String, Object>{input => null};

                            return new Map<String, Object>{
                            input.substringBefore('.') => get(input.substringAfter('.'))
                            };

                            }
                            }


                            Then executing:



                            System.debug(JSON.serialize(MyClass.get('Root.Parent.FirstChild')));


                            Output : {"Root":{"Parent":{"FirstChild":null}}







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 30 at 12:32









                            Pranay Jaiswal

                            12.9k32251




                            12.9k32251






















                                up vote
                                3
                                down vote













                                One of the approaches would be create a inner wrapper class for Map, and define own method to set value based on path.



                                Most of the code is already written in your question, so check the following pseudo-code:



                                public class SuperMap {
                                Map<String, Object> ResultMap;

                                public SuperMap() {
                                ResultMap = new Map<String, Object>();
                                }

                                public void specifyValue(String path, Object value) {
                                Map<String, Object> current_map = ResultMap;
                                List<String> path_steps = path.split('\.');
                                for(Integer i = 0; i < path_steps.size() - 1; i++) {
                                String step = path_steps.get(i);
                                if (!current_map.containsKey(step)) {
                                current_map.put(step, (Object)new Map<String, Object>());
                                }
                                current_map = (Map<String, Object>)current_map.get(step);
                                }
                                current_map.put(path_steps.get(path_steps.size() - 1), value);
                                }
                                public String returnString() {
                                return JSON.serialize(ResultMap);
                                }
                                }


                                Example of usage:



                                SuperMap mp = new SuperMap();
                                mp.specifyValue('kuru.123.dev','Data');
                                mp.specifyValue('grey.123.dev2','Data2');
                                mp.specifyValue('grey.123.dev2','Data3');
                                System.debug(mp.returnString());





                                share|improve this answer

























                                  up vote
                                  3
                                  down vote













                                  One of the approaches would be create a inner wrapper class for Map, and define own method to set value based on path.



                                  Most of the code is already written in your question, so check the following pseudo-code:



                                  public class SuperMap {
                                  Map<String, Object> ResultMap;

                                  public SuperMap() {
                                  ResultMap = new Map<String, Object>();
                                  }

                                  public void specifyValue(String path, Object value) {
                                  Map<String, Object> current_map = ResultMap;
                                  List<String> path_steps = path.split('\.');
                                  for(Integer i = 0; i < path_steps.size() - 1; i++) {
                                  String step = path_steps.get(i);
                                  if (!current_map.containsKey(step)) {
                                  current_map.put(step, (Object)new Map<String, Object>());
                                  }
                                  current_map = (Map<String, Object>)current_map.get(step);
                                  }
                                  current_map.put(path_steps.get(path_steps.size() - 1), value);
                                  }
                                  public String returnString() {
                                  return JSON.serialize(ResultMap);
                                  }
                                  }


                                  Example of usage:



                                  SuperMap mp = new SuperMap();
                                  mp.specifyValue('kuru.123.dev','Data');
                                  mp.specifyValue('grey.123.dev2','Data2');
                                  mp.specifyValue('grey.123.dev2','Data3');
                                  System.debug(mp.returnString());





                                  share|improve this answer























                                    up vote
                                    3
                                    down vote










                                    up vote
                                    3
                                    down vote









                                    One of the approaches would be create a inner wrapper class for Map, and define own method to set value based on path.



                                    Most of the code is already written in your question, so check the following pseudo-code:



                                    public class SuperMap {
                                    Map<String, Object> ResultMap;

                                    public SuperMap() {
                                    ResultMap = new Map<String, Object>();
                                    }

                                    public void specifyValue(String path, Object value) {
                                    Map<String, Object> current_map = ResultMap;
                                    List<String> path_steps = path.split('\.');
                                    for(Integer i = 0; i < path_steps.size() - 1; i++) {
                                    String step = path_steps.get(i);
                                    if (!current_map.containsKey(step)) {
                                    current_map.put(step, (Object)new Map<String, Object>());
                                    }
                                    current_map = (Map<String, Object>)current_map.get(step);
                                    }
                                    current_map.put(path_steps.get(path_steps.size() - 1), value);
                                    }
                                    public String returnString() {
                                    return JSON.serialize(ResultMap);
                                    }
                                    }


                                    Example of usage:



                                    SuperMap mp = new SuperMap();
                                    mp.specifyValue('kuru.123.dev','Data');
                                    mp.specifyValue('grey.123.dev2','Data2');
                                    mp.specifyValue('grey.123.dev2','Data3');
                                    System.debug(mp.returnString());





                                    share|improve this answer












                                    One of the approaches would be create a inner wrapper class for Map, and define own method to set value based on path.



                                    Most of the code is already written in your question, so check the following pseudo-code:



                                    public class SuperMap {
                                    Map<String, Object> ResultMap;

                                    public SuperMap() {
                                    ResultMap = new Map<String, Object>();
                                    }

                                    public void specifyValue(String path, Object value) {
                                    Map<String, Object> current_map = ResultMap;
                                    List<String> path_steps = path.split('\.');
                                    for(Integer i = 0; i < path_steps.size() - 1; i++) {
                                    String step = path_steps.get(i);
                                    if (!current_map.containsKey(step)) {
                                    current_map.put(step, (Object)new Map<String, Object>());
                                    }
                                    current_map = (Map<String, Object>)current_map.get(step);
                                    }
                                    current_map.put(path_steps.get(path_steps.size() - 1), value);
                                    }
                                    public String returnString() {
                                    return JSON.serialize(ResultMap);
                                    }
                                    }


                                    Example of usage:



                                    SuperMap mp = new SuperMap();
                                    mp.specifyValue('kuru.123.dev','Data');
                                    mp.specifyValue('grey.123.dev2','Data2');
                                    mp.specifyValue('grey.123.dev2','Data3');
                                    System.debug(mp.returnString());






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 30 at 12:28









                                    kurunve

                                    2,39021022




                                    2,39021022






























                                        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.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • 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%2f241048%2fhow-to-create-a-recursive-method-in-apex-which-takes-a-dot-notation-string-and-c%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

                                        Quarter-circle Tiles

                                        build a pushdown automaton that recognizes the reverse language of a given pushdown automaton?

                                        Mont Emei