Help us understand the problem. What is going on with this article?

jsonを取得、表示するアプリケーション その5

More than 5 years have passed since last update.

レスポンスで取得したデータを整形する
ただこのままだと日本語がユニコードエスケープされたままになるので変換処理をかませる

json_client.groovy
import groovy.swing.SwingBuilder
import groovy.json.JsonOutput
import javax.swing.*
import java.awt.*

def cbMethod
def txtUrl
def txtParam
def txtJson

def tabPane

def prettyPrint = { text ->
    def result = JsonOutput.prettyPrint(text)
    (result =~ /\\u[0-9a-zA-Z]{4}/).each { match ->
        def code = match[2..5]
        def encTxt = new String([Integer.parseInt(code, 16)] as int[], 0, 1)
        result = result.replaceAll(/\\u${code}/, encTxt)
    }
    result
}

def sendRequest = {
    def url = txtUrl.text
    if (cbMethod.selectedItem == 'GET') {
        url = "${url}?${txtParam.text}"
    }

    def conn = url.toURL().openConnection()
    conn.requestMethod = cbMethod.selectedItem
    if (cbMethod.selectedItem == 'POST') {
        conn.doOutput = true
        conn.outputStream << txtParam.text
    }

    txtJson.text = prettyPrint(conn.inputStream.getText('utf-8'))
    tabPane.selectedIndex = 1
}

new SwingBuilder().frame(title:'jsonを取得、表示するアプリケーション', defaultCloseOperation:JFrame.EXIT_ON_CLOSE,
                        size: [800, 600], show:true) {
    lookAndFeel('nimbus')
    borderLayout()
    hbox(constraints: BorderLayout.NORTH) {
        cbMethod = comboBox(items:['GET', 'POST'])
        txtUrl = textField()
        button(text:'送信', actionPerformed:sendRequest)
    }
    tabPane = tabbedPane(constraints: BorderLayout.CENTER) {
        scrollPane(name:'パラメータ') {
            txtParam = textArea()
        }
        scrollPane(name:'レスポンス') {
            txtJson = textArea(editable:false)
        }
    }
}

qiita-005.png

hina0118
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away