Android/TIL
Gson을 이용하여 Assets에 있는 JSON 파일 읽기
Cha_Cha
2021. 8. 9. 00:51
Kotlin Android – Read JSON file from assets using Gson
Kotlin – Convert object to/from JSON string using Gson
1. Assets 폴더 생성 후 JSON 파일 생성하기
// communityData.json
{
"id": 1,
"contentsImages": [
"https://g-grafolio.pstatic.net/20190425_85/1556163852187Et6ao_JPEG/DSC02684.jpg?type=w896_4",
"http://shop1.phinf.naver.net/20200919_230/1600508769512eErFn_JPEG/8ge1j7f_202091214118493298.jpg",
"http://post.phinf.naver.net/20140312_291/3352763_1394560796781tXrgq_JPEG/mug_obj_201403120300032819.jpg",
"http://shop1.phinf.naver.net/20210606_128/1622980268594b5jWl_JPEG/30444900716438856_1037262977.jpg"
]
}
2. Data Class 생성하기
data class Posting(
val id: Long,
val contentsImages: List<String>
)
3. Assets 폴더에 있는 JSON 파일을 읽어오는 코드 생성
fun getJsonDataFromAsset(): String? {
val jsonString: String
try {
jsonString = requireActivity().assets.open("communityData.json")
.bufferedReader()
.use { it.readText() }
} catch (ioException: IOException) {
ioException.printStackTrace()
return null
}
return jsonString
}
4. Gson을 이용하여 JSON을 Kotlin Object로 파싱하기
Activity나 Fragment에서 Gson 라이브러리를 import하고 getJsonDataFromAsset 메소드 호출하기
// gson
implementation 'com.google.code.gson:gson:2.8.7'
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
val jsonString = getJsonDataFromAsset()
val gson = Gson()
val listPostingType = object : TypeToken<List<Posting>>() {}.type
// public <T> T fromJson(json, typeOfT) throws JsonSyntaxException
var postings: List<Posting> = gson.fromJson(jsonString, listPostingType)