Skip to content

Instantly share code, notes, and snippets.

@jarryDk jarryDk/Json2Yaml.java
Last active Dec 20, 2018

Embed
What would you like to do?
package dk.jarry.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.UUID;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
public class Json2Yaml {
private Path sourcePath;
private Path targetPath;
private Boolean replace = Boolean.FALSE;
public Json2Yaml() {
}
public Json2Yaml(Path sourcePath) {
this.sourcePath = sourcePath;
}
public Json2Yaml(Path sourcePath, Path targetPath) {
this.sourcePath = sourcePath;
this.targetPath = targetPath;
}
public Json2Yaml(Path sourcePath, Path targetPath, Boolean replace) {
this.sourcePath = sourcePath;
this.targetPath = targetPath;
this.replace = replace;
}
public String getYamlString() throws JsonParseException, JsonMappingException, IOException {
if (sourcePath == null) {
throw new IllegalArgumentException("sourcePath is null");
}
if (!Files.exists(sourcePath)) {
throw new IOException(sourcePath.toString() + " is not on disk");
}
String jsonString = new String(Files.readAllBytes(sourcePath));
return getYamlString(jsonString);
}
public String getYamlString(String jsonString) throws IOException {
JsonNode jsonNodeTree = new ObjectMapper().readTree(jsonString);
String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree);
return jsonAsYaml;
}
public void save() throws JsonParseException, JsonMappingException, IOException {
if (targetPath == null) {
targetPath = Paths.get(sourcePath.toString().replace(".json", ".yaml"));
}
if (Files.exists(targetPath)) {
if (replace) {
Files.delete(targetPath);
} else {
targetPath = Paths.get(targetPath.toString(), "_" + UUID.randomUUID().toString());
}
}
Files.write(targetPath, getYamlString().getBytes(), StandardOpenOption.CREATE);
}
}
/**
* Add to pom.xml
*
*<dependency>
* <groupId>com.fasterxml.jackson.dataformat</groupId>
* <artifactId>jackson-dataformat-yaml</artifactId>
* <version>2.9.5</version>
*</dependency>
*<dependency>
* <groupId>com.fasterxml.jackson.core</groupId>
* <artifactId>jackson-databind</artifactId>
* <version>2.9.5</version>
*</dependency>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.