我有一个字符串,我需要在API调用中作为JSON有效负载的一部分发送。 ...
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)
什么是最流行的方法来删除回车并转义JSON的引号(单引号和双引号)。
我知道第一个要求至少我可以使用正则表达式并按照this post中的建议替换所有Java。
但是只是想知道是否有一种更加便捷的方式来做到这一点并且也可以逃避报价?
答案 0 :(得分:1)
你确定需要吗? JsonBuilder
已经逃脱了:
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 "}}}'
否则,StringEscapeUtils
可能会引起人们的兴趣。