AbuMariam AbuMariam - 1 month ago 14
Groovy Question

How to remove carriage returns and escape quotes from a String in Groovy?

I have a string that I need to send in an API call as part of a JSON payload. ...

def aliciaSong = """
Moment of honesty
Someones gotta take the lead tonight


Who's it gonna be?
I'm gonna sit right here
And tell you all that comes to me
If "you" have something to say
"You" should say it right now
"""

def json = new groovy.json.JsonBuilder()
def songJson = json.songs {
song {
singer "Alicia"
lyrics lyricsStr.toString()

}
}

StringRequestEntity requestEntity = new StringRequestEntity(json.toString(), "application/json", "UTF-8")
httpMethod.setRequestEntity(requestEntity)
httpClient.executeMethod(emailSendMethod)


What is the grooviest way to both remove the carriage returns and escape the quotes for JSON (both single and double).

I know for the first requirement at least I can use regular expressions and replace all as suggested in this post for Java.

But just wondering if there was a groovier way to do it and escape the quotes as well?

Answer

Are you sure this is needed? JsonBuilder will already escape them:

 def alicia = """
 Moment of honesty
      Someones gotta take the lead tonight


     Who's it gonna be?
     I'm gonna sit right here
       And tell you all that comes to me
If "you" have something to say
    "You" should say it right now
 """

def json = new groovy.json.JsonBuilder()       
def songJson = json.songs {
song {
      singer "Alicia"
      lyrics alicia

  }
}

assert json.toString() == '{"songs":{"song":{"singer":"Alicia","lyrics":"\n Moment of honesty\n      Someones gotta take the lead tonight\n\n\n     Who's it gonna be?\n     I'm gonna sit right here\n       And tell you all that comes to me\nIf \"you\" have something to say\n    \"You\" should say it right now\n "}}}'

Otherwise, StringEscapeUtils might be of interest.