Skip to content

Instantly share code, notes, and snippets.

@boillodmanuel
Created April 23, 2015 09:27
Show Gist options
  • Save boillodmanuel/fc5fd75a75665ac13ea3 to your computer and use it in GitHub Desktop.
Save boillodmanuel/fc5fd75a75665ac13ea3 to your computer and use it in GitHub Desktop.
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* @author Manuel Boillod
*/
public class JsonUtils {
public static String toJson(Object object) {
StringWriter stringWriter = new StringWriter();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
try {
mapper.writeValue(stringWriter, object);
return stringWriter.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void toFile(String content, String filename) {
toFile(content, new File(filename));
}
public static void toFile(String content, File file) {
try {
Files.write(content,
file,
Charset.defaultCharset());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@glaforge
Copy link

Better use UTF-8 instead of defaultCharset, to avoid issues moving between different platforms with different encodings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment