Created
April 23, 2015 09:27
-
-
Save boillodmanuel/fc5fd75a75665ac13ea3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better use UTF-8 instead of defaultCharset, to avoid issues moving between different platforms with different encodings.