JsonToKotlinClass icon indicating copy to clipboard operation
JsonToKotlinClass copied to clipboard

Support creating Maps for json with dynamic keys

Open henrik242 opened this issue 6 years ago • 6 comments

My ~/.docker/config.json looks similar to this:

{
	"auths": {
		"containers.example.io": {},
		"https://containers.example.io": {
			"auth": "ZXhhbXBsZQo="
		}
	},
	"HttpHeaders": {
		"User-Agent": "Docker-Client/19.03.2 (darwin)"
	},
	"credsStore": "desktop"
}

.. but that gives me silly classes within "auths", like this:

data class DockerConfig(
    val auths: Auths,
    val HttpHeaders: HttpHeaders,
    val credsStore: String
)

data class Auths(
    val containers.example.io: Containersexampleio,
    val https://containers.example.io: HttpsContainersexampleio
)

class Containersexampleio(
)

data class HttpsContainersexampleio(
    val auth: String
)

data class HttpHeaders(
    val User-Agent: String
)

How would you suggest making data classes that properly parses different keys within "auths"? I guess preferrabbly it should be a Map<String, Auth> of some sort. The same thing applies to "HttpHeaders" (Map<String, String>).

I usually use com.fasterxml.jackson.module.kotlin.jacksonObjectMapper() to parse my json files.

henrik242 avatar Oct 29 '19 11:10 henrik242

I figured it out, this works fine:

data class DockerConfig(val auths: Map<String, Auth>?, val HttpHeaders: Map<String, String>?, val credsStore: String?)
data class Auth(val auth: String?)

Support for this in JsonToKotlinClass would be awesome :)

henrik242 avatar Oct 29 '19 12:10 henrik242

The problem is that how could plugin known when should the json object be parsed as map type, could you give any idea:smiley:

wuseal avatar Oct 29 '19 12:10 wuseal

Hmm, good question. Maybe have an option to say "parse all parameters below level n as Maps"?

henrik242 avatar Oct 29 '19 14:10 henrik242

Hmm, good question. Maybe have an option to say "parse all parameters below level n as Maps"?

Some times this method may not fit. for map type may need to be parsed in several levels, not at the same level. I think the more appropriate method may be that adding a tag on the JSON object to indicate the JSON object should be parsed into map type instead of a data class by the user.

wuseal avatar Nov 03 '19 14:11 wuseal

That's true, but it would could be helpful to partially generate the wanted data classes

henrik242 avatar Nov 03 '19 16:11 henrik242

@henrik242 How could we achieve those, can you give some details or examples?

wuseal avatar Nov 10 '19 12:11 wuseal