[application] JSON 문서 사용하기

PUJIN·2023년 7월 21일
0

코딩 - 프로젝트

목록 보기
5/13
post-thumbnail

API 데이터 형태




AndroidManifest.xml

  • INTERNET permission 설정
<uses-permission android:name="android.permission.INTERNET"/>

MainActivity

  • API 주소 입력
val serverAddress = "API 주소"
  • JSON 파일 읽어오기
thread {
	// URL 객체 생성
	val url = URL(serverAddress)
	// 접속 후 스트림 추출
	val httpURLConnection = url.openConnection() as HttpURLConnection

	val inputStreamReader = InputStreamReader(httpURLConnection.inputStream, "UTF-8")
	// 라인 단위로 읽어오기
	val bufferedReader = BufferedReader(inputStreamReader)

	var str:String? = null
	val stringBuffer = StringBuffer()
                    
	// 문서의 마지막까지 읽어오기
	do{
		str = bufferedReader.readLine()
		if(str != null){
			stringBuffer.append(str)
		}
	}while(str != null)

	val data = stringBuffer.toString()

	runOnUiThread{
		textView.text = ""
	}
}
  • JSON 데이터 분석
    • { } : JSONObject
      • 이름 - 값 형태
    • [ ] : JSONArray
      • 0부터 1씩 증가하는 순서값 형태
thread {
	val root = JSONObject(data)

	val boardsArray = root.getJSONArray("boards")

	for(idx in 0 until boardsArray.length()) {
		val boardsObject = boardsArray.getJSONObject(idx)
		val board = boardsObject.getString("board")
		val title = boardsObject.getString("title")
		val pages = boardsObject.getInt("pages")
		val image_limit = boardsObject.getInt("image_limit")

		val cooldowns = boardsObject.getJSONObject("cooldowns")
		val threads = cooldowns.getInt("threads")
		val replies = cooldowns.getInt("replies")
		val images = cooldowns.getInt("images")

		runOnUiThread {
			textViewData.append("board : $board\n")
			textViewData.append("title : $title\n")
			textViewData.append("pages : $pages\n")
			textViewData.append("image_limit : $image_limit\n")
			textViewData.append("[cooldowns]\n")
			textViewData.append("threads : $threads\n")
			textViewData.append("replies : $replies\n")
			textViewData.append("images : $images\n\n")
		}
	}
}

활용 API (Free and Open Public APIs)

1개의 댓글

comment-user-thumbnail
2023년 7월 21일

API를 활용한 데이터 처리에 대한 내용이 상세하게 잘 설명되어 있어, 많은 도움이 되었습니다. 특히 JSON 데이터 분석 부분을 이해하는데 크게 도움이 되었네요. 좋은 정보 공유 감사드립니다!

답글 달기

관련 채용 정보