LoginSignup
1
1

More than 5 years have passed since last update.

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

Posted at

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

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

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1