Access nested JsonNode elements and separate by comma

Viewed 167

I have the following Json object:

 myJson = {1: {"grade": "A"}, 23: {"grade": "B"} }

I would like to iterate through the grades and if there is more than one grade, then I'd like to have the following string:

"A, B"

Separated by comma. If there is one element, then only "A".

How do I loop through the nested json object to delimit them by comma ? It is a JsonNode Jackson. Thank you.

2 Answers

First of all, your JSON payload is not valid and you need to enable JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES option. Also, you need to register KotlinModule.

Simple example could look like below:

import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import java.io.File
import java.io.IOException
import java.util.stream.Collectors

@Throws(IOException::class)
fun main(args: Array<String>) {
    val jsonFile = File("src/main/resources/test.json").absoluteFile
    val mapper = ObjectMapper()
        .registerKotlinModule()
        .findAndRegisterModules()
        .enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
    val grades = mapper.readValue<ObjectNode>(jsonFile)
        .findValues("grade")
        .stream()
        .map { v -> v.asText() }
        .collect(Collectors.joining(", "))
    System.out.println(grades)
}

Above code prints:

A, B

You can get the desired result like this (Java):

String s = myJson.findValuesAsText("grade").stream()
                 .collect(Collectors.joining(", "));
Related