Reputation: 73
[
{
"ReserveNumber": "RN001",
"RecordType": "Bsdfs",
"RequireType": "BBsdfdsdf"
}, {
"ReserveNumber": "RN002",
"RecordType": "Breer",
"RequireType": "BBertert"
}, {
"ReserveNumber": "RN001",
"RecordType": "Brete",
"RequireType": "BBdvdv"
}, {
"ReserveNumber": "RN003",
"RecordType": "Berretert",
"RequireType": "BBxcvvd"
}
]
In the above JSON array, each JSON object contains ReserveNumber
element. Here how to find the count of reservation number if it occurs multiple times? Here ReserveNumber
RN001
occurred twice. How to find it using GSON library in Kotlin?
Upvotes: 0
Views: 606
Reputation: 1787
I don't do Kotlin, but it seems to be pretty easy in Kotlin (and even simpler than using Java 8 Streams API):
fun group(input: JsonArray): JsonArray {
return input.map { it.getAsJsonObject().getAsJsonPrimitive("ReserveNumber").asString }
.groupingBy { it }
.eachCount()
.entries
.fold(JsonArray(), { jsonArray, e ->
val el = JsonObject()
el.addProperty("key", e.key)
el.addProperty("count", e.value)
jsonArray.add(el)
jsonArray
})
}
The function above is not generic and can be improved if necessary, but now for your JSON document it can produce the following JSON array (similar to what you've referred to: How to get repeated objects in json array in javascript in your first comment, but with another output JSON object property names):
[
{"key": "RN001", "count": 2},
{"key": "RN002", "count": 1},
{"key": "RN003", "count": 1}
]
Upvotes: 1
Reputation: 2476
You can do it in a couple of ways. But the most simple one is using GSON itself
1- Build a class that represents your JSON object
2- Build a Map<String, Int> that represents the ReserveNumber
and the count
3- Iterate through the objects and add to the count
Upvotes: 1