I'm using JsonBuilder to create a new Json object. Additionally I have to do an escaping of control and special charaters.
Therefore I'm using the JsonOutput.toJson which adds an additional "content" element.
sample XML input:
<?xml version="1.0" encoding="utf-8"?>
<TestRequest>
<Note>test note....ÄäÜü ß / $ % § "</Note>
<Note2>This is another note. here comes the Zeilenumbruch...bruch
...hier geh's weiter
</Note2>
</TestRequest>
sample coding:
class Mapping_41_Test_Control_Chars {
static main(args) {
def in_xml = new XmlSlurper().parse("./test/Sample_Control_Character.xml")
def jsonBuilder = new JsonBuilder()
jsonBuilder{
note in_xml.Note.toString()
note2 in_xml.Note2.toString()
}
println "-------- prettyPrint_JsonOutput.toJson:"
println JsonOutput.prettyPrint(JsonOutput.toJson(jsonBuilder));
def json = JsonOutput.toJson([note: 'test note....ÄäÜü ß / $ % § "'])
println "-------- json:"
println JsonOutput.prettyPrint(json)
}
JsonOutput.toJson:
-------- prettyPrint_JsonOutput.toJson:
{
"content": {
"note": "test note....\u00c4\u00e4\u00dc\u00fc \u00df / $ % \u00a7 \"",
"note2": "This is another note. here comes the Zeilenumbruch...bruch\n...hier geh's weiter\n"
}
}
-------- json:
{
"note": "John Doe",
"age": "test note....\u00c4\u00e4\u00dc\u00fc \u00df / $ % \u00a7 \""
}
Do you know an option to use JsonOutput with JsonBuilder and get the required output eliminating the "content" element? I need to escape the special characters therefore I cannot use toString
Thanks & Regards Marco
You don't have to use JsonOutput.toJson()
when working with JsonBuilder
- it has a method JsonBuilder.toPrettyString()
that creates a String
representation of your JSON object.
import groovy.json.JsonBuilder
def builder = new JsonBuilder()
builder {
name 'John Doe'
age 99
}
println builder.toPrettyString()
{
"name": "John Doe",
"age": 99
}