Created
May 19, 2017 15:57
-
-
Save guillaumegarcia13/3423a285ca8c5317c63a547db7f5bc25 to your computer and use it in GitHub Desktop.
Java JSONUtils
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
public class JSONUtils { | |
//------------- | |
// DATA | |
//------------- | |
static public ObjectMapper objectMapper = new ObjectMapper(); | |
//------------- | |
// METHODS | |
//------------- | |
static public String object2JSON(Object obj) { | |
return object2JSON(obj, false); | |
} | |
static public String object2JSON(Object obj, boolean pretty) { | |
String json = null; | |
ObjectWriter objectWriter = (pretty) ? objectMapper.writerWithDefaultPrettyPrinter() : objectMapper.writer(); | |
try { | |
json = objectWriter.writeValueAsString(obj); | |
} | |
catch (JsonProcessingException e) { | |
e.printStackTrace(); | |
} | |
return json; | |
} | |
static public Map<String, Object> object2Map(Object obj) { | |
Map<String, Object> map = null; | |
map = objectMapper.convertValue(obj, Map.class); | |
return map; | |
} | |
static public Map<String, Object> object2Map(Object obj, String... keepFields) { | |
Map<String, Object> map = object2Map(obj); | |
HashSet<String> keySet = new HashSet<String>(map.keySet()); | |
keySet.removeAll(new HashSet<String>(Arrays.asList(keepFields))); | |
// /!\ D A N G E R /!\ | |
// -> this triggers: java.util.ConcurrentModificationException | |
// for (String key : keySet) { | |
// map.remove(key); | |
// } | |
HashSet<String> removeSet = (HashSet<String>) keySet.clone(); | |
for (String key : removeSet) { | |
map.remove(key); | |
} | |
return map; | |
} | |
public static void main(String[] args) { | |
Email email = new Email(); | |
email.setId(123); | |
System.out.println(JSONUtils.object2Map(email, "id")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment