$ mvn archetype:generate -DgroupId=com.jsontoenum.app -DartifactId=json-to-enum -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
$ cd json-to-enum/ && mvn package
<dependency>
<groupId>com.typesafe</groupId>
<artifactId>config</artifactId>
<version>1.3.4</version>
</dependency>
<resources>
<resource>
<directory>src/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
{
"swiss": {
"cheese": "gruyere"
}
}
package com.jsontoenum.app;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
public class App {
public static void main(String[] args) {
// Load and init the configuration library
final Config conf = ConfigFactory.load();
// Get the value of the JSON property
final String cheese = conf.getString("swiss.cheese");
System.out.println(String.format("I like %s 🧀", cheese));
}
}
$ mvn package && java -cp target/json-to-enum-1.0-SNAPSHOT.jar com.jsontoenum.app.App
package com.jsontoenum.app;
public enum Cheese {
GRUYERE,
TETE_DE_MOINE,
CHAUX_DABEL,
RACLETTE,
VACHERIN,
TOMME
}
private static <E extends Enum<E>> E getEnumProperty(final Config conf, final String key, final Class<E> myClass) {
// If no config loaded
if (conf == null) {
return null;
}
// If the config doesn't contains the key
if (!conf.hasPath(key)) {
return null;
}
// As previously, load the key value
final String keyValue = conf.getString(key);
// Does the property has a value
if (keyValue == null || keyValue.isEmpty()) {
return null;
}
// Map the property to the ENUM
return Enum.valueOf(myClass, keyValue.toUpperCase());
}
public static void main(String[] args) {
// Load and init the configuration library
final Config conf = ConfigFactory.load();
// Get the value of the JSON property
final Cheese cheese =
getEnumProperty(conf, "swiss.cheese", Cheese.class);
if (Cheese.GRUYERE.equals(cheese)) {
System.out.println(String.format("I really like %s 🧀", cheese));
} else {
System.out.println(String.format("%s is ok", cheese));
}
}
[INFO] ------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------
[INFO] Total time: 2.437 s
[INFO] Finished at: 2019-08-16T15:43:42+02:00
[INFO] ------------------------------------------------------------
I really like GRUYERE 🧀
$ git clone https://github.com/peterpeterparker/json-to-enum.git