Simple way to read Json file on android studio

4.9k Views Asked by At

I have a JSON file containing a list of countries and I want to integrate it into my android studio java project then read the content via code, where to put the file in the project and what's the easiest way to read the file in my Java classes?

Thank you!

1

There are 1 best solutions below

2
qki On
  1. Firstly, you have to read the file and assign the content to some string variable

         val file = File(context?.filesDir, FILE_NAME)
     val fileReader = FileReader(File(context?.filesDir, FILE_NAME))
     val bufferedReader = BufferedReader(fileReader)
     val stringBuilder = StringBuilder()
     var line = bufferedReader.readLine()
     while (line != null) {
         stringBuilder.append("${line}\n")
         line = bufferedReader.readLine()
     }
     bufferedReader.close()
     val jsonFileAsString = stringBuilder.toString()
    

2.Secondly, you have to create a JSONOBJECT from the previous result (the jsonFileAsString variable)

 val jsonObject = JSONObject(jsonFileAsString)
  1. Finally, to read a specific property you can use

    jsonObject.get("name").toString()

But to make things clear you should consider making a data class to match specific JSON file and parse it that way. To do this you can use GSON library (I dunno if standard Android packages have this functionality) and you should get something like this:

the data class

data class Transport(
    val TransportIdentifier: String?,
    val TransportType: String?,
)

and to parse it you simply use

val transport = Gson().fromJson<Transport>(stringVariable, Transport::class.java)

and can use it like

transport.TransportType

To make things even more simplier, you can generate a data class from the JSON output using for example online-parser