Skip to content

Instantly share code, notes, and snippets.

@trfiladelfo
Last active April 16, 2020 15:53
Show Gist options
  • Save trfiladelfo/d77b97cb1e4ab561b57f87f5a9ceb219 to your computer and use it in GitHub Desktop.
Save trfiladelfo/d77b97cb1e4ab561b57f87f5a9ceb219 to your computer and use it in GitHub Desktop.
Exemplo de conversão de JSON para classe
import org.json.JSONObject
import org.json.JSONArray
class Task(val title:String, val email:String, val description:String) {
fun convertToJSON(): JSONObject {
val json = JSONObject()
json.put("title", title)
json.put("email", email)
json.put("description", description)
return json
}
}
class Tasks(){
val tasks = arrayListOf<Task>()
fun convertToObject(items: JSONArray): ArrayList<Task> {
(0 until items.length()).forEach {
tasks.add(Task(it.getString("title"), it.getString("email"), it.getString("description"))
}
return tasks
}
}
fun main() {
val body = """{"data":[{"_id":"adf0f707-b6c7-4167-be34-83a73950d36e","description":"lorem ipsum","email":"sofie@mysofie.com","when":"2020-04-15T19:14:39.094560","title":"tarefa 4"},{"_id":"372efad7-9c69-4753-bf9b-ee7741aaed0c","description":"lorem ipsum","email":"sofie@sofie.com","when":"2020-04-15T15:41:49.074693","title":"tarefa 3"},{"_id":"15893f63-17b4-4ef3-bc69-019fda35c339","description":"lorem ipsum","email":"sofie@sofie.com","when":"2020-04-15T15:39:19.126486","title":"tarefa 2"}]}""".trimMargin()
val tasks = Tasks().convertToObject(body.getJSONArray("data"))
val task = tasks[0]
val title = task.title
val email = task.email
val json = task.convertToJSON()
println(json)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment