I’m beginner in Groovy, I do JSON parsing and export data to a csv file, but it turns out like in the screenshot. How can I better write it in the code so that the data is correct when exporting to a file, or do I need to convert the csv file itself to UTF-8?
import groovy.json.JsonSlurper
def conn = "http://jira.server.net:8080/rest/api/2/project/".toURL().openConnection()
conn.setRequestProperty('Authorization', 'Basic ' + 'login:password'.bytes.encodeBase64().toString())
if(conn.responseCode == 200) {
def jsonSlurper = new JsonSlurper()
def data = jsonSlurper.parseText(conn.content.text)
def file = new File("C:/Temp/data.csv")
def stringBuilder = new StringBuilder()
data.each { row ->
stringBuilder.append(row.join(';')).append(System.lineSeparator())
}
file.text = stringBuilder.toString()
} else {
println "Something bad happened."
println "${conn.responseCode}: ${conn.responseMessage}"
}
Result:
Разработка СПО ПТСПК версии
2
Answers
Setting up encoding should fix it.
conn.content
returnsInputStream
(something like
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
)when you transform it to text with
conn.content.text
– you actually callingInputStream.getText()
you can convert input stream to text with
InputStream.getText("UTF-8")
or you can parse the input stream into json without text:
https://docs.groovy-lang.org/latest/html/gapi/groovy/json/JsonSlurper.html#parse(java.io.InputStream,%20java.lang.String)