Created
July 22, 2013 07:39
-
-
Save mothman88/6051977 to your computer and use it in GitHub Desktop.
Converting Java Objects to Byte Array, JSON and XML
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
/** | |
* Convert object to byte array | |
* @param object | |
* @return | |
*/ | |
public static byte[] fromJavaToByteArray(Serializable object) { | |
return SerializationUtils.serialize(object); | |
} | |
/** | |
* Convert byte array to object | |
* @param bytes | |
* @return | |
*/ | |
public static Object fromByteArrayToJava(byte[] bytes) { | |
return SerializationUtils.deserialize(bytes); | |
} | |
/** | |
* Convert object to JSON String | |
* @param object | |
* @return | |
* @throws JsonGenerationException | |
* @throws JsonMappingException | |
* @throws IOException | |
*/ | |
public static String fromJavaToJson(Serializable object) | |
throws JsonGenerationException, JsonMappingException, IOException { | |
ObjectMapper jsonMapper = new ObjectMapper(); | |
return jsonMapper.writeValueAsString(object); | |
} | |
/** | |
* Convert a JSON string to an object | |
* @param json | |
* @return | |
* @throws JsonParseException | |
* @throws JsonMappingException | |
* @throws IOException | |
*/ | |
public static Object fromJsonToJava(String json, Class type) throws JsonParseException, | |
JsonMappingException, IOException { | |
ObjectMapper jsonMapper = new ObjectMapper(); | |
return jsonMapper.readValue(json, type); | |
} | |
/** | |
* Convert a java object to XML | |
* @param object | |
* @return | |
*/ | |
public static String fromJavaToXML(Serializable object) { | |
XStream xs = new XStream(); | |
return xs.toXML(object); | |
} | |
/** | |
* Convert from XML to object | |
* @param xml | |
* @return | |
*/ | |
public static Object fromXMLToJava(String xml){ | |
XStream xs = new XStream(); | |
return xs.fromXML(xml); | |
} |
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
<dependency> | |
<groupId>commons-lang</groupId> | |
<artifactId>commons-lang</artifactId> | |
<version>2.6</version> | |
</dependency> | |
<dependency> | |
<groupId>org.codehaus.jackson</groupId> | |
<artifactId>jackson-mapper-asl</artifactId> | |
<version>1.9.12</version> | |
</dependency> | |
<dependency> | |
<groupId>com.thoughtworks.xstream</groupId> | |
<artifactId>xstream</artifactId> | |
<version>1.4.4</version> | |
</dependency> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment