Fzee
Fzee

Reputation: 33

Looping in kotlin in line

i have some trouble in using kotlin for looping

i have json as like below :

{
idEvent: "584412",
strEvent: "Huesca vs Girona",
strHomeYellowCards: "28':Ezequiel Avila;34':Juan Nunez Aguilera;45':Damian Musto;88':David Ferreiro;"
}

and after i generate in android studio, i want the line strHomeYellowCards become like below in only one TextView:

Ezequiel Avila 28'
Juan Nunez Aguilera 34'
Damian Musto 45' 
David Ferreiro 88'

and these my code to make it happened

fun formatNumPlayer(players: String?): String {
        if (players.isNullOrBlank()) {
            return players.orEmpty()
        } else {
            val entered = players!!.replace(";", "\n")
            val splitted = entered!!.split(":")
            var result: String? = null
            for (i in splitted.indices) {
                result += "${splitted[1]}" + " " + "${splitted[0]}" + "\n"
            }
            return result!!
        }
    }

but the result is under my expectation, so how the true code about it?

Upvotes: 0

Views: 774

Answers (3)

Maik Peschutter
Maik Peschutter

Reputation: 613

He can't use Gson because the minute:player pair is separated by ; In a valid json this has to be a ,

If your really want to parse this manually, try this:

fun formatNumPlayer(players: String?): String {
    var result = ""
    players?.let {
        it.split(";").forEach { pair ->
            val tmp = pair.split(":")
            result += tmp[1] + " " + tmp[0] + "\n"
        }
        return result
    }

    return result
}

Upvotes: 0

Michael Lam
Michael Lam

Reputation: 445

The JSON provided is not a well formatted JSON. So i assume that you just pasted the key:value pair here.

In this case, taking the value as a string and processing it would be the easiest way to achieve your goal.

// Assume bulkText is the value of key `strHomeYellowCards`
val bulkText = "28':Ezequiel Avila;34':Juan Nunez Aguilera;45':Damian Musto;88':David Ferreiro;"

var result = ""

bulkText.split(';').forEach{
    result += it.split(':').asReversed().reduce{ sum, element -> sum + ' ' + element } + '\n'
}

// result should be your desired output
println(result)

Upvotes: 1

Ernest Zamelczyk
Ernest Zamelczyk

Reputation: 2819

First of all the JSON you provided in your question doesn't have correct format. It should be more like this:

strHomeYellowCards: [
  {
    "minute": "28'",
    "player": "Ezequiel Avila"
  },
  {
    "minute": "34'",
    "player": "Juan Nunez Aguilera"
  }, ..and so on
]

And then you can move on to parsing it. For parsing JSON object you should use a library like GSON.

Create POJO object for your YellowCard:

data class YellowCard(
    @SerializedName("minute") val minute: String, 
    @SerializedName("player") val player: String)

And then for parsing it:

val gson = Gson()
val yellowCards: List<YellowCard> = gson.fromJson(json, new TypeToken<List<YellowCard>>(){}.getType())

Upvotes: 0

Related Questions