skip to Main Content

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


  1. Setting up encoding should fix it.

    file.withWriter('UTF-8'){ it << stringBuilder }
    
    Login or Signup to reply.
  2. conn.content returns InputStream

    (something like sun.net.www.protocol.http.HttpURLConnection$HttpInputStream)

    when you transform it to text with conn.content.text – you actually calling InputStream.getText()

    you can convert input stream to text with InputStream.getText("UTF-8")

    or you can parse the input stream into json without text:

    def data = jsonSlurper.parse(conn.content, "UTF-8")
    

    https://docs.groovy-lang.org/latest/html/gapi/groovy/json/JsonSlurper.html#parse(java.io.InputStream,%20java.lang.String)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search