===== Json 읽기 =====
==== 1. Json 스트링에서 Json 요소 읽기 ====
Json 요소를 뽑아내는 코드는 다음과 같다.
val json = LoadFileFromUri(uri = result.value, contentResolver)
// Json 문장에서 Json 요소 뽑아내기
try {
val jsonObject : JSONObject = JSONObject(json);
predictions.value = jsonObject.getString("predictions")
val jsonArray : JSONArray = JSONArray(predictions.value)
for (i in 0..jsonArray.length())
{
val subjsonObject : JSONObject = jsonArray.getJSONObject(i)
description.value += "description : " + subjsonObject.getString("description") + "\n" + "id : " + subjsonObject.getString("id") + "\n"
val structured_formatting : String = subjsonObject.getString("structured_formatting");
val subJsonObject2 : JSONObject = JSONObject(structured_formatting);
main_text.value += subJsonObject2.getString("main_text") + "\n"
}
} catch (e : JSONException) {
e.printStackTrace();
}
==== 2. Json 스트링 만들기 ====
파일 Uri를 인자로 하여 Json 스트링을 만드는 방법은 다음과 같다.
// 파일 내용 읽어서 String으로 만들기
fun LoadFileFromUri(uri: Uri?, cr : ContentResolver) : String {
var words : String = ""
if(uri==null) {
Log.e("LoadFileFromUri", "Unable to load the file")
} else {
val inputStream = cr.openInputStream(uri)
val reader = BufferedReader(InputStreamReader(inputStream))
var line = reader.readLine()
words += line + "\n"
while (line != null) {
Log.d("LoadFileFromUri", line)
line = reader.readLine()
words += line + "\n"
}
}
return words
}
==== 3. 파일피커로 Json 요소 읽는 전체 소스 ====
파일피커로 Json 파일을 읽는다면 다음과 같이 만들면 된다.
// 파일 픽커
val contentResolver = LocalContext.current.contentResolver
val result = remember { mutableStateOf(null) }
val predictions = remember { mutableStateOf("") }
val description = remember { mutableStateOf("") }
val main_text = remember { mutableStateOf("") }
val pickJsonFileLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.OpenDocument())
{
result.value = it
notification.value = result.value.toString()
val json = LoadFileFromUri(uri = result.value, contentResolver)
// Json 문장에서 Json 요소 뽑아내기
try {
val jsonObject : JSONObject = JSONObject(json);
predictions.value = jsonObject.getString("predictions")
val jsonArray : JSONArray = JSONArray(predictions.value)
for (i in 0..jsonArray.length())
{
val subjsonObject : JSONObject = jsonArray.getJSONObject(i)
description.value += "description : " + subjsonObject.getString("description") + "\n" + "id : " + subjsonObject.getString("id") + "\n"
val structured_formatting : String = subjsonObject.getString("structured_formatting");
val subJsonObject2 : JSONObject = JSONObject(structured_formatting);
main_text.value += subJsonObject2.getString("main_text") + "\n"
}
} catch (e : JSONException) {
e.printStackTrace();
}
}