JRobi17X
JRobi17X

Reputation: 67

Is there a way to serialize all values of an enum with JSON in Kotlin?

I have the following enum:

enum class Difficulty {
    EASY, MEDIUM, HARD
}

My Rest API is working in the following way: I have classes, and every class has a classManagementService, which helps to list every Response. Like this:

@Service
class RecipeManagementService (@Autowired private val recipeRepository: RecipeRepository,
                               private val addRecipeRequestTransformer: AddRecipeRequestTransformer) {

    fun findAll(): List<RecipeResponse> = this.recipeRepository.findAll().map(Recipe::toRecipeResponse)

RecipeResource.kt

@RestController
@RequestMapping(value = [BASE_RECIPE_URL])
class RecipeResource(private val recipeManagementService: RecipeManagementService)
{
    @GetMapping
    fun findAll(): ResponseEntity<List<RecipeResponse>> = ResponseEntity.ok(this.recipeManagementService.findAll())

RecipeResponse.kt

data class RecipeResponse (var id:Long,
                           var name:String,
                           var ingredient:List<Ingredient>?,
                           var process:String?,
                           var category: List<Category>?,
                           var difficulty: Difficulty?)

I want the /api/v1/difficulty request to list all the difficulties. Is there a way to do this?

Upvotes: 0

Views: 402

Answers (1)

Joffrey
Joffrey

Reputation: 37809

Every enum class has a generated values() method you can use to get an array of all possible values:

val allDifficulties: Array<Difficulty> = Difficulty.values()

So you can just return that in your controller, or use toList() if you want to return a List.

Upvotes: 3

Related Questions