0

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 Answers1

0
  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

qki
  • 1,769
  • 11
  • 25
  • thanks for your answer, my file is actually a .json not .txt, does it make any difference? and also where should I put it on my project? – YOUSFI Mohamed Walid Sep 23 '20 at 14:18
  • it doesn't make any difference. Where you should put it depends on if you are getting the file via some WebApi or is it a static file that you are using throughout the whole app – qki Sep 23 '20 at 14:21