DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Generics in Java and Their Implementation
  • Speeding Up Large Collections Processing in Java
  • Working With Data in Microservices
  • SmartXML: An Alternative to XPath for Complex XML Files

Trending

  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • GDPR Compliance With .NET: Securing Data the Right Way
  • A Guide to Developing Large Language Models Part 1: Pretraining
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  1. DZone
  2. Coding
  3. Java
  4. Converting Java Objects to Byte Array, JSON and XML

Converting Java Objects to Byte Array, JSON and XML

Quick reference for converting Java objects to various formats (byte array, JSON, XML) and back, using different libraries for serialization and deserialization.

By 
Faheem Sohail user avatar
Faheem Sohail
·
Jul. 22, 13 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
106.3K Views

Join the DZone community and get the full member experience.

Join For Free

Converting a Java object (a process known as serialization) to various forms such as XML, JSON, or a byte array and back into java objects is a very common requirement. This post is intended to be a quick reference for you to easily make these conversions.

Java Object to Byte Array and Back

Lets start by converting a java object into a byte array and back. The library we will be using to achieve this result is the commons lang library which you can get using the following maven dependency.

<dependency>
	<groupId>commons-lang</groupId>
	<artifactId>commons-lang</artifactId>
	<version>2.6</version>
</dependency>

The following two functions convert a java object to a byte array and back to java object respectively. You will need the following import:

import org.apache.commons.lang.SerializationUtils;

…

/**
* 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);
}

Java Object to JSON and Back

Next, we will convert a java object to JSON and back to java. We will use the Jackson library for this. Use the following maven dependency.

<dependency>
	<groupId>org.codehaus.jackson</groupId>
	<artifactId>jackson-mapper-asl</artifactId>
	<version>1.9.12</version>
</dependency>

The functions that perform the conversions.

/**
* 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);
}

Java Object to XML and Back

We will use Xstream from thoughtworks to serialize to XML. Include the following maven dependency.

<dependency>
	<groupId>com.thoughtworks.xstream</groupId>
	<artifactId>xstream</artifactId>
	<version>1.4.4</version>
</dependency>

And the one-liners to perform the conversions.

/**
* 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);
}





JSON XML Java (programming language) Object (computer science) Data Types Data structure

Published at DZone with permission of Faheem Sohail, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Generics in Java and Their Implementation
  • Speeding Up Large Collections Processing in Java
  • Working With Data in Microservices
  • SmartXML: An Alternative to XPath for Complex XML Files

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!