Convert flat object hierarchy to json












0














I do work for a project currently, where the data is send to the server as application/x-www-form-urlencoded (which is bad, and it should be JSON, but unfortunately I am not able to change this one).



The following code snipped will transfer the given parameters (in a loop) to a Map, which can then be transformed to json (eg. by using jackson).



I would like to make this even better, so please post your comments and suggestions.



Parameter-List:



_id=[5bfad95450642c333010daca], 
_rev=[1-9ce33949c3acd85cea6c58467e6a8144],
type=[Group],
user=[aUSer],
default=[aDetail],
store[aDetail][prop]=[5],
store[aDetail][lprop1][0][time]=[00:00],
store[aDetail][lprop1][0][value]=[14],
store[aDetail][lprop1][0][timeAsSeconds]=[0],
store[aDetail][lprop1][1][time]=[07:00],
store[aDetail][lprop1][1][value]=[8],
store[aDetail][lprop1][1][timeAsSeconds]=[25200],
store[aDetail][anprop]=[25],
store[aDetail][lprop2][0][time]=[00:00],
store[aDetail][lprop2][0][value]=[61],
store[aDetail][lprop2][0][timeAsSeconds]=[0],
store[bDetail][prop]=[6],
store[bDetail][lprop1][0][time]=[00:10],
store[bDetail][lprop1][0][value]=[12],
store[bDetail][lprop1][0][timeAsSeconds]=[0],
store[bDetail][lprop1][1][time]=[07:10],
store[bDetail][lprop1][1][value]=[9],
store[bDetail][lprop1][1][timeAsSeconds]=[25200],
store[bDetail][anprop]=[25],
store[bDetail][lprop2][0][time]=[00:00],
store[bDetail][lprop2][0][value]=[61],
store[bDetail][lprop2][0][timeAsSeconds]=[0],
created_at=[2018-01-11T20:48:22.574+0100],
...


Code-Snippet:



fun parseToMap(map: MutableMap<String, Any>, key: String, value: Any): MutableMap<String, Any> {
val cleanedV = if (value is String) URLDecoder.decode(value, "UTF-8") else value

if (!key.contains("[")) {
map.putIfAbsent(key, cleanedV)
} else {
// mapKey is the key going to get stored in the map
val mapKey = key.substring(0, key.indexOf("["))

// nextKey is the next key pushed to the next call of parseToMap
var nextKey = key.removePrefix(mapKey)
nextKey = nextKey.replaceFirst("[", "").replaceFirst("]", "")

var isArray = false
var index = -1

if (nextKey.contains("[") &&
nextKey.substring(0, nextKey.indexOf("[")).matches(Regex("[0-9]+"))) {
index = nextKey.substring(0, nextKey.indexOf("[")).toInt()
isArray = true
}

// mapkey used for object in list
val newMapKey = if (isArray) nextKey.substring(nextKey.indexOf("[") + 1, nextKey.indexOf("]")) else ""

val child: Any?
var childMap: MutableMap<String, Any> = mutableMapOf()

if (map.containsKey(mapKey)) {
println("key $mapKey exists already")
child = map[mapKey]

when (child) {
is MutableList<*> -> {
if (child == null || child.isEmpty()) {
childMap = mutableMapOf()
val tmpList = child as MutableList<Any>
tmpList.add(childMap)
map.put(newMapKey, tmpList)
} else {
if (child.size > index) {
childMap = child.get(index) as MutableMap<String, Any>
childMap = parseToMap(childMap, newMapKey, value)
} else {
childMap = parseToMap(childMap, newMapKey, value)
val tmpList = child as MutableList<Any>
tmpList.add(childMap)
}
}
}
is MutableMap<*, *> -> childMap = map.get(mapKey) as MutableMap<String, Any>
}
} else {
if (isArray) {
child = mutableListOf<Any>()
childMap = parseToMap(childMap, newMapKey, value)
child.add(childMap)
map.put(mapKey, child)
} else {
childMap = mutableMapOf<String, Any>()
}
}

if (!isArray) parseToMap(childMap, nextKey, value)

map.putIfAbsent(mapKey, childMap)
}

return map
}


Calling this method:



    decodedParameters.forEach { k, v -> run {
val cleanedV = v.toString().replace("[", "").replace("]", "")
jsonMap = parseToMap(jsonMap, k, cleanedV)
} }









share|improve this question







New contributor




triplem is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    0














    I do work for a project currently, where the data is send to the server as application/x-www-form-urlencoded (which is bad, and it should be JSON, but unfortunately I am not able to change this one).



    The following code snipped will transfer the given parameters (in a loop) to a Map, which can then be transformed to json (eg. by using jackson).



    I would like to make this even better, so please post your comments and suggestions.



    Parameter-List:



    _id=[5bfad95450642c333010daca], 
    _rev=[1-9ce33949c3acd85cea6c58467e6a8144],
    type=[Group],
    user=[aUSer],
    default=[aDetail],
    store[aDetail][prop]=[5],
    store[aDetail][lprop1][0][time]=[00:00],
    store[aDetail][lprop1][0][value]=[14],
    store[aDetail][lprop1][0][timeAsSeconds]=[0],
    store[aDetail][lprop1][1][time]=[07:00],
    store[aDetail][lprop1][1][value]=[8],
    store[aDetail][lprop1][1][timeAsSeconds]=[25200],
    store[aDetail][anprop]=[25],
    store[aDetail][lprop2][0][time]=[00:00],
    store[aDetail][lprop2][0][value]=[61],
    store[aDetail][lprop2][0][timeAsSeconds]=[0],
    store[bDetail][prop]=[6],
    store[bDetail][lprop1][0][time]=[00:10],
    store[bDetail][lprop1][0][value]=[12],
    store[bDetail][lprop1][0][timeAsSeconds]=[0],
    store[bDetail][lprop1][1][time]=[07:10],
    store[bDetail][lprop1][1][value]=[9],
    store[bDetail][lprop1][1][timeAsSeconds]=[25200],
    store[bDetail][anprop]=[25],
    store[bDetail][lprop2][0][time]=[00:00],
    store[bDetail][lprop2][0][value]=[61],
    store[bDetail][lprop2][0][timeAsSeconds]=[0],
    created_at=[2018-01-11T20:48:22.574+0100],
    ...


    Code-Snippet:



    fun parseToMap(map: MutableMap<String, Any>, key: String, value: Any): MutableMap<String, Any> {
    val cleanedV = if (value is String) URLDecoder.decode(value, "UTF-8") else value

    if (!key.contains("[")) {
    map.putIfAbsent(key, cleanedV)
    } else {
    // mapKey is the key going to get stored in the map
    val mapKey = key.substring(0, key.indexOf("["))

    // nextKey is the next key pushed to the next call of parseToMap
    var nextKey = key.removePrefix(mapKey)
    nextKey = nextKey.replaceFirst("[", "").replaceFirst("]", "")

    var isArray = false
    var index = -1

    if (nextKey.contains("[") &&
    nextKey.substring(0, nextKey.indexOf("[")).matches(Regex("[0-9]+"))) {
    index = nextKey.substring(0, nextKey.indexOf("[")).toInt()
    isArray = true
    }

    // mapkey used for object in list
    val newMapKey = if (isArray) nextKey.substring(nextKey.indexOf("[") + 1, nextKey.indexOf("]")) else ""

    val child: Any?
    var childMap: MutableMap<String, Any> = mutableMapOf()

    if (map.containsKey(mapKey)) {
    println("key $mapKey exists already")
    child = map[mapKey]

    when (child) {
    is MutableList<*> -> {
    if (child == null || child.isEmpty()) {
    childMap = mutableMapOf()
    val tmpList = child as MutableList<Any>
    tmpList.add(childMap)
    map.put(newMapKey, tmpList)
    } else {
    if (child.size > index) {
    childMap = child.get(index) as MutableMap<String, Any>
    childMap = parseToMap(childMap, newMapKey, value)
    } else {
    childMap = parseToMap(childMap, newMapKey, value)
    val tmpList = child as MutableList<Any>
    tmpList.add(childMap)
    }
    }
    }
    is MutableMap<*, *> -> childMap = map.get(mapKey) as MutableMap<String, Any>
    }
    } else {
    if (isArray) {
    child = mutableListOf<Any>()
    childMap = parseToMap(childMap, newMapKey, value)
    child.add(childMap)
    map.put(mapKey, child)
    } else {
    childMap = mutableMapOf<String, Any>()
    }
    }

    if (!isArray) parseToMap(childMap, nextKey, value)

    map.putIfAbsent(mapKey, childMap)
    }

    return map
    }


    Calling this method:



        decodedParameters.forEach { k, v -> run {
    val cleanedV = v.toString().replace("[", "").replace("]", "")
    jsonMap = parseToMap(jsonMap, k, cleanedV)
    } }









    share|improve this question







    New contributor




    triplem is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      0












      0








      0







      I do work for a project currently, where the data is send to the server as application/x-www-form-urlencoded (which is bad, and it should be JSON, but unfortunately I am not able to change this one).



      The following code snipped will transfer the given parameters (in a loop) to a Map, which can then be transformed to json (eg. by using jackson).



      I would like to make this even better, so please post your comments and suggestions.



      Parameter-List:



      _id=[5bfad95450642c333010daca], 
      _rev=[1-9ce33949c3acd85cea6c58467e6a8144],
      type=[Group],
      user=[aUSer],
      default=[aDetail],
      store[aDetail][prop]=[5],
      store[aDetail][lprop1][0][time]=[00:00],
      store[aDetail][lprop1][0][value]=[14],
      store[aDetail][lprop1][0][timeAsSeconds]=[0],
      store[aDetail][lprop1][1][time]=[07:00],
      store[aDetail][lprop1][1][value]=[8],
      store[aDetail][lprop1][1][timeAsSeconds]=[25200],
      store[aDetail][anprop]=[25],
      store[aDetail][lprop2][0][time]=[00:00],
      store[aDetail][lprop2][0][value]=[61],
      store[aDetail][lprop2][0][timeAsSeconds]=[0],
      store[bDetail][prop]=[6],
      store[bDetail][lprop1][0][time]=[00:10],
      store[bDetail][lprop1][0][value]=[12],
      store[bDetail][lprop1][0][timeAsSeconds]=[0],
      store[bDetail][lprop1][1][time]=[07:10],
      store[bDetail][lprop1][1][value]=[9],
      store[bDetail][lprop1][1][timeAsSeconds]=[25200],
      store[bDetail][anprop]=[25],
      store[bDetail][lprop2][0][time]=[00:00],
      store[bDetail][lprop2][0][value]=[61],
      store[bDetail][lprop2][0][timeAsSeconds]=[0],
      created_at=[2018-01-11T20:48:22.574+0100],
      ...


      Code-Snippet:



      fun parseToMap(map: MutableMap<String, Any>, key: String, value: Any): MutableMap<String, Any> {
      val cleanedV = if (value is String) URLDecoder.decode(value, "UTF-8") else value

      if (!key.contains("[")) {
      map.putIfAbsent(key, cleanedV)
      } else {
      // mapKey is the key going to get stored in the map
      val mapKey = key.substring(0, key.indexOf("["))

      // nextKey is the next key pushed to the next call of parseToMap
      var nextKey = key.removePrefix(mapKey)
      nextKey = nextKey.replaceFirst("[", "").replaceFirst("]", "")

      var isArray = false
      var index = -1

      if (nextKey.contains("[") &&
      nextKey.substring(0, nextKey.indexOf("[")).matches(Regex("[0-9]+"))) {
      index = nextKey.substring(0, nextKey.indexOf("[")).toInt()
      isArray = true
      }

      // mapkey used for object in list
      val newMapKey = if (isArray) nextKey.substring(nextKey.indexOf("[") + 1, nextKey.indexOf("]")) else ""

      val child: Any?
      var childMap: MutableMap<String, Any> = mutableMapOf()

      if (map.containsKey(mapKey)) {
      println("key $mapKey exists already")
      child = map[mapKey]

      when (child) {
      is MutableList<*> -> {
      if (child == null || child.isEmpty()) {
      childMap = mutableMapOf()
      val tmpList = child as MutableList<Any>
      tmpList.add(childMap)
      map.put(newMapKey, tmpList)
      } else {
      if (child.size > index) {
      childMap = child.get(index) as MutableMap<String, Any>
      childMap = parseToMap(childMap, newMapKey, value)
      } else {
      childMap = parseToMap(childMap, newMapKey, value)
      val tmpList = child as MutableList<Any>
      tmpList.add(childMap)
      }
      }
      }
      is MutableMap<*, *> -> childMap = map.get(mapKey) as MutableMap<String, Any>
      }
      } else {
      if (isArray) {
      child = mutableListOf<Any>()
      childMap = parseToMap(childMap, newMapKey, value)
      child.add(childMap)
      map.put(mapKey, child)
      } else {
      childMap = mutableMapOf<String, Any>()
      }
      }

      if (!isArray) parseToMap(childMap, nextKey, value)

      map.putIfAbsent(mapKey, childMap)
      }

      return map
      }


      Calling this method:



          decodedParameters.forEach { k, v -> run {
      val cleanedV = v.toString().replace("[", "").replace("]", "")
      jsonMap = parseToMap(jsonMap, k, cleanedV)
      } }









      share|improve this question







      New contributor




      triplem is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I do work for a project currently, where the data is send to the server as application/x-www-form-urlencoded (which is bad, and it should be JSON, but unfortunately I am not able to change this one).



      The following code snipped will transfer the given parameters (in a loop) to a Map, which can then be transformed to json (eg. by using jackson).



      I would like to make this even better, so please post your comments and suggestions.



      Parameter-List:



      _id=[5bfad95450642c333010daca], 
      _rev=[1-9ce33949c3acd85cea6c58467e6a8144],
      type=[Group],
      user=[aUSer],
      default=[aDetail],
      store[aDetail][prop]=[5],
      store[aDetail][lprop1][0][time]=[00:00],
      store[aDetail][lprop1][0][value]=[14],
      store[aDetail][lprop1][0][timeAsSeconds]=[0],
      store[aDetail][lprop1][1][time]=[07:00],
      store[aDetail][lprop1][1][value]=[8],
      store[aDetail][lprop1][1][timeAsSeconds]=[25200],
      store[aDetail][anprop]=[25],
      store[aDetail][lprop2][0][time]=[00:00],
      store[aDetail][lprop2][0][value]=[61],
      store[aDetail][lprop2][0][timeAsSeconds]=[0],
      store[bDetail][prop]=[6],
      store[bDetail][lprop1][0][time]=[00:10],
      store[bDetail][lprop1][0][value]=[12],
      store[bDetail][lprop1][0][timeAsSeconds]=[0],
      store[bDetail][lprop1][1][time]=[07:10],
      store[bDetail][lprop1][1][value]=[9],
      store[bDetail][lprop1][1][timeAsSeconds]=[25200],
      store[bDetail][anprop]=[25],
      store[bDetail][lprop2][0][time]=[00:00],
      store[bDetail][lprop2][0][value]=[61],
      store[bDetail][lprop2][0][timeAsSeconds]=[0],
      created_at=[2018-01-11T20:48:22.574+0100],
      ...


      Code-Snippet:



      fun parseToMap(map: MutableMap<String, Any>, key: String, value: Any): MutableMap<String, Any> {
      val cleanedV = if (value is String) URLDecoder.decode(value, "UTF-8") else value

      if (!key.contains("[")) {
      map.putIfAbsent(key, cleanedV)
      } else {
      // mapKey is the key going to get stored in the map
      val mapKey = key.substring(0, key.indexOf("["))

      // nextKey is the next key pushed to the next call of parseToMap
      var nextKey = key.removePrefix(mapKey)
      nextKey = nextKey.replaceFirst("[", "").replaceFirst("]", "")

      var isArray = false
      var index = -1

      if (nextKey.contains("[") &&
      nextKey.substring(0, nextKey.indexOf("[")).matches(Regex("[0-9]+"))) {
      index = nextKey.substring(0, nextKey.indexOf("[")).toInt()
      isArray = true
      }

      // mapkey used for object in list
      val newMapKey = if (isArray) nextKey.substring(nextKey.indexOf("[") + 1, nextKey.indexOf("]")) else ""

      val child: Any?
      var childMap: MutableMap<String, Any> = mutableMapOf()

      if (map.containsKey(mapKey)) {
      println("key $mapKey exists already")
      child = map[mapKey]

      when (child) {
      is MutableList<*> -> {
      if (child == null || child.isEmpty()) {
      childMap = mutableMapOf()
      val tmpList = child as MutableList<Any>
      tmpList.add(childMap)
      map.put(newMapKey, tmpList)
      } else {
      if (child.size > index) {
      childMap = child.get(index) as MutableMap<String, Any>
      childMap = parseToMap(childMap, newMapKey, value)
      } else {
      childMap = parseToMap(childMap, newMapKey, value)
      val tmpList = child as MutableList<Any>
      tmpList.add(childMap)
      }
      }
      }
      is MutableMap<*, *> -> childMap = map.get(mapKey) as MutableMap<String, Any>
      }
      } else {
      if (isArray) {
      child = mutableListOf<Any>()
      childMap = parseToMap(childMap, newMapKey, value)
      child.add(childMap)
      map.put(mapKey, child)
      } else {
      childMap = mutableMapOf<String, Any>()
      }
      }

      if (!isArray) parseToMap(childMap, nextKey, value)

      map.putIfAbsent(mapKey, childMap)
      }

      return map
      }


      Calling this method:



          decodedParameters.forEach { k, v -> run {
      val cleanedV = v.toString().replace("[", "").replace("]", "")
      jsonMap = parseToMap(jsonMap, k, cleanedV)
      } }






      parsing http hash-map kotlin






      share|improve this question







      New contributor




      triplem is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      triplem is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      triplem is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 13 mins ago









      triplem

      1011




      1011




      New contributor




      triplem is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      triplem is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      triplem is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.



























          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          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
          });


          }
          });






          triplem is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210599%2fconvert-flat-object-hierarchy-to-json%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          triplem is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          triplem is a new contributor. Be nice, and check out our Code of Conduct.













          triplem is a new contributor. Be nice, and check out our Code of Conduct.












          triplem is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review 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.


          Use MathJax to format equations. MathJax reference.


          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%2fcodereview.stackexchange.com%2fquestions%2f210599%2fconvert-flat-object-hierarchy-to-json%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

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'