Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map to String/String to Map conversion in Groovy

I have a json object that gets passed into a save function as

{
  "markings": {
      "headMarkings": "Brindle",
      "leftForeMarkings": "",
      "rightForeMarkings": "sock",
      "leftHindMarkings": "sock",
      "rightHindMarkings": "",
      "otherMarkings": ""
}

** EDIT **

The system parses it and passes it to my function as a mapping. I don't actually have the JSON, although it wouldn't be difficult to build up the JSON myself, it just seems like overkill

* END EDIT **

The toString() function ends up putting the results into the database as

"[rightForeMarkings:, otherMarkings:, leftForeMarkings:sock, leftHindMarkings:sock, rightHindMarkings:, headMarkings:brindle]"

I then want to save that as a string (fairly easy) by calling

params.markings.toString()

From here, I save the info and return the updated information.

My issue is that since I am storing the object in the DB as a string, I can't seem to get the markings back out as a map (to then be converted to JSON).

I have tried a few different things to no avail, although it is completely possible that I went about something incorrectlywith these...

Eval.me(Item.markings)
evaluate(Item.markings)
Item.markings.toList()

Thanks in advance for the help!

like image 836
David Ziemann Avatar asked Dec 26 '22 00:12

David Ziemann


1 Answers

Throwing my tests.

Using JSON converters in Grails, I think this should be the approach: (synonymous to @JamesKleeh and @GrailsGuy)

def json = '''{
                  "markings": {
                      "headMarkings": "Brindle",
                      "leftForeMarkings": "",
                      "rightForeMarkings": "sock",
                      "leftHindMarkings": "sock",
                      "rightHindMarkings": "",
                      "otherMarkings": ""
                   }
                }'''

def jsonObj = grails.converters.JSON.parse(json)
//This is your JSON object that should be passed in to the method
print jsonObj //[markings:[rightForeMarkings:sock, otherMarkings:, leftForeMarkings:, leftHindMarkings:sock, rightHindMarkings:, headMarkings:Brindle]]

def jsonStr = jsonObj.toString()
//This is the string which should be persisted in db
assert jsonStr == '{"markings":{"rightForeMarkings":"sock","otherMarkings":"","leftForeMarkings":"","leftHindMarkings":"sock","rightHindMarkings":"","headMarkings":"Brindle"}}'

//Get back json obj from json str
def getBackJsobObj = grails.converters.JSON.parse(jsonStr)
assert getBackJsobObj.markings.leftHindMarkings == 'sock'
like image 154
dmahapatro Avatar answered Dec 28 '22 14:12

dmahapatro