Kotlin – Convert Object to/from XML File (XML String) by Jackson

In the tutorial, we will show how to convert XML String/File to Object and versus by Kotlin language with Jackson.

Jackson XML Dataformat

For serialize/deserialize Object to XML and versus, we use ‘Jackson Dataformat XML’ dependency:

<dependency>
	<groupId>com.fasterxml.jackson.dataformat</groupId>
	<artifactId>jackson-dataformat-xml</artifactId>
	<version>2.9.4</version>
</dependency>

Write Kotlin object to XML

Create model:


package com.javasampleapproach.kotlin.xml.model

data class Address(
	val street: String = "",
	val postcode: String = ""
)
package com.javasampleapproach.kotlin.xml.model

data class Customer(
	val name: String = "",
	val age: Int = -1,
	val address: Address? = null
)

Kotlin object to XML String

Use writeValueAsString(obj: Object): String:


val xmlMapper = XmlMapper()
val strObject = xmlMapper.writeValueAsString(object)

Kotlin object to XML File

Use writeValue(File resultFile, Object value): Unit:


val xmlMapper = XmlMapper()
xmlMapper.writeValue(File(pathFile), object)

Program – Kotlin object to XML


package com.javasampleapproach.kotlin.xml

import java.io.File
import java.io.IOException
 
import com.fasterxml.jackson.core.JsonGenerationException
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.JsonMappingException
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import com.javasampleapproach.kotlin.xml.model.Customer
import com.javasampleapproach.kotlin.xml.model.Address

fun main(args: Array) {
	
	val customer = Customer("Mary", 37, Address("NANTERRE CT", "77471"))
	
	// 1. Write Object to XML String
    val xml = write2XMLString(customer)
    
    println(xml);
    /*
		
		
		   Mary
		   37
		   
NANTERRE CT 77471
*/ // 2. Write Object to XML File val pathFile = System.getProperty("user.dir") + "\\customer.xml" write2XMLFile(customer, pathFile) // -> content of customer.xml file: /* Mary 37
NANTERRE CT 77471
*/ } /* * Convert Object to XML String */ fun write2XMLString(obj: Any): String { val xmlMapper = XmlMapper() // use the line of code for pretty-print XML on console. We should remove it in production. xmlMapper.enable(SerializationFeature.INDENT_OUTPUT); return xmlMapper.writeValueAsString(obj) } /* * Write Object to XML file */ fun write2XMLFile(obj: Any, pathFile: String) { val xmlMapper = XmlMapper() // use the line of code for pretty-print XML on console. We should remove it in production. xmlMapper.enable(SerializationFeature.INDENT_OUTPUT) xmlMapper.writeValue(File(pathFile), obj) }

Convert XML to Kotlin object

XML String to Kotlin object

Use readValue(content: String, valueType: Class<*>):


val xmlString = 	"" + 
					"  Mary" + 
					"  37" + 
					"  
" + " NANTERRE CT" + " 77471" + "
" + "
" val xmlMapper = XmlMapper() val obj = xmlMapper.readValue(xmlString, cls)

XML File to Kotlin object

Use readValue(src: File, valueType: Class<*>):


val xmlMapper = XmlMapper()
val obj = xmlMapper.readValue(new File(pathFile), cls)

Program – XML to Kotlin object


package com.javasampleapproach.kotlin.model

import java.io.File;
import java.io.IOException;
 
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import com.javasampleapproach.kotlin.xml.model.Customer

fun main(args: Array) {
	/*
	 * 1. Convert String XML to Object
	 */
	val xmlString = 	"" + 
						"  Mary" + 
						"  37" + 
						"  
" + " NANTERRE CT" + " 77471" + "
" + "
" var customer = convertXmlString2DataObject(xmlString, Customer::class.java) println(customer) // -> Customer[name=Mary, age=37, Address[street=NANTERRE CT, postcode=77471]] /* * 2. Convert XML File to Object */ val pathFile = System.getProperty("user.dir") + "\\customer.xml" customer = convertXmlFile2DataObject(pathFile, Customer::class.java) println(customer) // -> Customer[name=Mary, age=37, Address[street=NANTERRE CT, postcode=77471]] } fun convertXmlString2DataObject(xmlString: String, cls: Class<*>): Any { val xmlMapper = XmlMapper() return xmlMapper.readValue(xmlString, cls) } fun convertXmlFile2DataObject(pathFile: String, cls: Class<*>): Any{ val xmlMapper = XmlMapper() return xmlMapper.readValue(File(pathFile), cls) }

16 thoughts on “Kotlin – Convert Object to/from XML File (XML String) by Jackson”

  1. I was curious if you ever thought of changing the page layout of your site?

    Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having one or two images.
    Maybe you could space it out better?

  2. Write more, thats all I have to say. Literally, it seems as
    though you relied on the video to make your point. You obviously know
    what youre talking about, why throw away your intelligence on just posting
    videos to your blog when you could be giving us something informative to
    read?

  3. Hi there, this weekend is nice in support of me,
    for the reason that this moment i am reading this impressive informative piece of writing here at my home.

  4. Hello there, just became alert to your blog through Google, and
    found that it’s truly informative. I’m going to watch
    out for brussels. I’ll appreciate if you continue this in future.
    Many people will be benefited from your writing. Cheers!

  5. Ηi there! Thіѕ blog post could not be written aany betteг!
    Looking through this post reminds me oof my pгevious roommate!
    He always kept talking about this. I’ll send this information to him.

    Fairly certain he’ll have a very good read.

    I appreciate you for sharing!

  6. Great beat ! I would like to apprentice while you amend your site,
    how can i subscribe for a blog web site? The account aided me a acceptable deal.
    I had been tiny bit acquainted of this your broadcast provided bright clear
    concept

  7. Hello this is kinda of off topic but I was wanting to know
    if blogs use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding know-how so I wanted to get
    advice from someone with experience. Any help would be enormously appreciated!

  8. І ⅼike the valuable information yⲟu pr᧐vide in youг articlеѕ.
    I will bookmаrk your weblߋg and check aɡain here frequently.
    I’m quitе sure I will learn lots of new stuff right here!

    Best of ⅼjcк for the next!

  9. Amazing things here. I am very happy to peer
    your post. Thanks so much and I’m taking a look ahead to touch you.
    Will you please drop me a e-mail?

  10. Oh mmү goodness! Amazing article dude! Thank you sso much, However Ӏ am eⲭpeiencing difficulties
    with your RSS. I don’t understand the reason ᴡhy I can’t subѕcrbe to it.
    Is there anybody ggetting the same RSS problems? Anyone that knows the answer caan you kindly respond?
    Thanx!!

  11. I thin this is one of the mоst inportant info for me.
    And i am glaԁ reading youг articⅼe. But should remark
    on some general things, The web site style is perfect, the articles is really nice : D.
    Good job, cheers

  12. Hey! І could have sworn I’ve Ьeen tto this website before but after browsing through som of the
    pst I realized it’s new to me. Anyhow, I’m definitely ɗelighhted
    Ifound iit and I’ll be book-marking and checking bacк frequently!

Leave a Reply

Your email address will not be published. Required fields are marked *