사용자 도구

사이트 도구


android:json파싱하기
json파싱하기

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판이전 판
다음 판
이전 판
android:json파싱하기 [2024/12/22 01:33] 이거니맨android:json파싱하기 [2025/04/23 23:37] (현재) 이거니맨
줄 140: 줄 140:
     var etcDetail: String = "", // 기타 기본 값     var etcDetail: String = "", // 기타 기본 값
 ) )
 +
 +</code> 
 +
 +==== 4. 배열(JSON Array) ====
 +
 +배열로 저장하고 싶으면 JSON Array를 선언해 주고, 여기에 JSON 모델을 집어넣으면 된다. 다음 예제를 참고하라.
 +
 +<code kotlin>
 +// JSON Array로 스트링 만들기
 +fun writeJsonArray(answerTexts : ArrayList<AnswerText>) : String {
 +
 +
 +    //JsonArray 생성
 +    val jArray: JSONArray = JSONArray()
 +
 +    answerTexts.forEach() {
 +        // 폭행 종류 JSON
 +        val jsonAnswer = JSONObject()
 +        try {
 +            jsonAnswer.put("text", it.text)
 +            jsonAnswer.put("correctness", it.correctness)
 +            jsonAnswer.put("index", it.index)
 +
 +            jArray.put(jsonAnswer)
 +        } catch (e: JSONException) {
 +            // TODO Auto-generated catch block
 +            e.printStackTrace()
 +        }
 +    }
 +
 +
 +
 +    return jArray.toString()
 +}
  
 </code> </code>
줄 264: 줄 298:
 } }
  
 +
 +</code>
 +
 +==== 4. 배열로 읽어 오기 ====
 +
 +배열로 읽는 것은 다음과 같이 하면 된다. 
 +
 +<code kotlin>
 +// 스트링에서 JSON 배열을 돌려주는 함수 
 +fun getJsonAnswerText(jsonText : String) : ArrayList<AnswerText> {
 +
 +    try {
 +        val jsonArray = JSONArray(jsonText)
 +
 +        val textArray = ArrayList<AnswerText>(jsonArray.length())
 +
 +        for (i in 0 until jsonArray.length()) {
 +            val jsonObject = jsonArray[i] as JSONObject
 +
 +            val valueOfAnswer : AnswerText = AnswerText(
 +                text = jsonObject.optString("text", "").first(),
 +                correctness = jsonObject.optString("correctness", "false").toBoolean(),
 +                index = jsonObject.optString("index", "0").toInt()
 +
 +            )
 +
 +            textArray.add(valueOfAnswer)
 +        }
 +
 +        return textArray
 +    }catch (e: JSONException) {
 +        // TODO Auto-generated catch block
 +        e.printStackTrace()
 +    }
 +    
 +    //  아래 코드는 만약에 에러가 날 경우에만 돌려주는 더미 배열이다. 
 +    val textArray = ArrayList<AnswerText>()
 +
 +    return textArray
 +
 +}
  
 </code> </code>
android/json파싱하기.1734798838.txt.gz · 마지막으로 수정됨: 2024/12/22 01:33 저자 이거니맨