Java – Convert Json(String/File) to/from XML(String/File)

In the tutorial provided by programming assignment experts from Assignmentcore.com, we show how to convert Json to XML and vice versa with Java language by examples.

Json dependency

For convert Json to/from XML we use JSONObject, so we need a dependency:


<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20180130</version>
</dependency>

Convert Json to XML

Convert Json String to XML String

String jsonStr = "{\"Customer\": {" +
						"\"address\": {" +
							"\"street\": \"NANTERRE CT\"," +
							"\"postcode\": 77471" +
						"}," + 
						"\"name\": \"Mary\"," +
						"\"age\": 37" +
					"}}";

JSONObject json = new JSONObject(jsonStr);
String xml = XML.toString(json);

System.out.println(xml);
/*
	
NANTERRE CT77471
Mary37
*/
Convert Json File to XML file

String jsonFile = System.getProperty("user.dir") + "\\file.json";
String xmlFile = System.getProperty("user.dir") + "\\file.xml";

jsonStr = new String(Files.readAllBytes(Paths.get(jsonFile)));
json = new JSONObject(jsonStr);

try (FileWriter fileWriter = new FileWriter(xmlFile)){
	fileWriter.write(XML.toString(json));
}
Full Program

package com.javasampleapproach.jsonxml;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.json.JSONObject;
import org.json.XML;

public class ConvertJson2Xml {
	public static void main(String[] args) throws IOException {
		
		// 1. Convert Json String -> XML String
		String jsonStr = "{\"Customer\": {" +
							    "\"address\": {" +
							        "\"street\": \"NANTERRE CT\"," +
							        "\"postcode\": 77471" +
							    "}," + 
							    "\"name\": \"Mary\"," +
							    "\"age\": 37" +
							"}}";
		
		JSONObject json = new JSONObject(jsonStr);
		String xml = XML.toString(json);
		
		System.out.println(xml);
		/*
		 	
NANTERRE CT77471
Mary37
--> pretty-print
NANTERRE CT 77471
Mary 37
*/ // 2. Convert Json File -> XML File String jsonFile = System.getProperty("user.dir") + "\\file.json"; String xmlFile = System.getProperty("user.dir") + "\\file.xml"; jsonStr = new String(Files.readAllBytes(Paths.get(jsonFile))); json = new JSONObject(jsonStr); try (FileWriter fileWriter = new FileWriter(xmlFile)){ fileWriter.write(XML.toString(json)); } } }

Convert XML to Json

Convert XML String to Json String

int PRETTY_PRINT_INDENT_FACTOR = 4;

String xmlString = 	"" + 
		"  Mary" + 
		"  37" + 
		"  
" + " NANTERRE CT" + " 77471" + "
" + "
"; JSONObject xmlJSONObj = XML.toJSONObject(xmlString); String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR); System.out.println(jsonPrettyPrintString); /* {"Customer": { "address": { "street": "NANTERRE CT", "postcode": 77471 }, "name": "Mary", "age": 37 }} */
Convert XML File to Json File

String xmlFile = System.getProperty("user.dir") + "\\file.xml";

xmlString = new String(Files.readAllBytes(Paths.get(xmlFile)));
xmlJSONObj = XML.toJSONObject(xmlString);

String jsonFile = System.getProperty("user.dir") + "\\file.json";

try (FileWriter fileWriter = new FileWriter(jsonFile)){
	fileWriter.write(xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR));
}
Full Program

package com.javasampleapproach.jsonxml;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.json.JSONObject;
import org.json.XML;

public class ConvertXml2Json {
	public static void main(String[] args) throws IOException {
		
		// 1. Convert XML String -> Json String
		int PRETTY_PRINT_INDENT_FACTOR = 4;
		
		String xmlString = 	"" + 
				"  Mary" + 
				"  37" + 
				"  
" + " NANTERRE CT" + " 77471" + "
" + "
"; JSONObject xmlJSONObj = XML.toJSONObject(xmlString); String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR); System.out.println(jsonPrettyPrintString); /* {"Customer": { "address": { "street": "NANTERRE CT", "postcode": 77471 }, "name": "Mary", "age": 37 }} */ // 2. Convert XML File -> Json File String xmlFile = System.getProperty("user.dir") + "\\file.xml"; xmlString = new String(Files.readAllBytes(Paths.get(xmlFile))); xmlJSONObj = XML.toJSONObject(xmlString); String jsonFile = System.getProperty("user.dir") + "\\file.json"; try (FileWriter fileWriter = new FileWriter(jsonFile)){ fileWriter.write(xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR)); } } }

66 thoughts on “Java – Convert Json(String/File) to/from XML(String/File)”

  1. Hi,

    Thanks for article.

    We also has library underscore-java with static methods U.xmlToJson(xml) and U.jsonToXml(json).

    Kind regards, Valentyn

  2. Thanks for expressing your ideas with this blog. Additionally, a delusion regarding the lenders intentions if talking about foreclosure is that the bank will not take my repayments. There is a certain quantity of time which the bank will take payments here and there. If you are also deep inside the hole, they may commonly call that you pay the actual payment fully. However, that doesn’t mean that they will have any sort of payments at all. Should you and the traditional bank can have the ability to work a thing out, the particular foreclosure course of action may end. However, in case you continue to neglect payments within the new strategy, the foreclosures process can just pick up exactly where it left off.

  3. Does your website have a contact page? I’m having problems locating it but, I’d like to shoot you an e-mail. I’ve got some ideas for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it develop over time.

  4. Hello would you mind stating which blog platform you’re working with? I’m going to start my own blog in the near future but I’m having a difficult time choosing between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something completely unique. P.S My apologies for getting off-topic but I had to ask!

  5. Thanks for this excellent article. One other thing is that many digital cameras are available equipped with a new zoom lens that allows more or less of your scene to get included by ‘zooming’ in and out. These kinds of changes in the aim length are reflected while in the viewfinder and on significant display screen right at the back of the specific camera.

  6. Thanks for this excellent article. One other thing is that most digital cameras can come equipped with a new zoom lens that enables more or less of a scene to generally be included by means of ‘zooming’ in and out. These kind of changes in focus length are generally reflected in the viewfinder and on large display screen right at the back of the exact camera.

  7. Simply want to say your article is as astonishing. The clarity to your submit is just excellent and i could assume you are an expert in this subject. Well together with your permission let me to seize your feed to keep up to date with approaching post. Thank you 1,000,000 and please keep up the enjoyable work.

  8. I抦 not sure where you are getting your information, but good topic. I needs to spend some time learning much more or understanding more. Thanks for magnificent info I was looking for this info for my mission.

  9. Thank you for another informative site. Where else could I get that type of information written in such a perfect way? I have a project that I am just now working on, and I have been on the look out for such information.

  10. Something more important is that when looking for a good on the internet electronics store, look for online shops that are consistently updated, always keeping up-to-date with the most recent products, the most beneficial deals, plus helpful information on product or service. This will make sure that you are dealing with a shop which stays over the competition and offers you things to make educated, well-informed electronics buying. Thanks for the significant tips I’ve learned from your blog.

  11. Hey there would you mind letting me know which webhost you’re using? I’ve loaded your blog in 3 different internet browsers and I must say this blog loads a lot quicker then most. Can you recommend a good hosting provider at a reasonable price? Kudos, I appreciate it!

  12. I’ve learned some important things as a result of your post. I will also like to mention that there will be a situation that you will apply for a loan and do not need a cosigner such as a Fed Student Support Loan. But if you are getting a loan through a common lender then you need to be prepared to have a co-signer ready to make it easier for you. The lenders will certainly base that decision on a few components but the most important will be your credit ratings. There are some loan companies that will likewise look at your work history and decide based on this but in many instances it will depend on your scores.

  13. Does your site have a contact page? I’m having problems locating it but, I’d like to shoot you an email. I’ve got some creative ideas for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it grow over time.

  14. Hmm it appears like your blog ate my first comment (it was extremely long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to the whole thing. Do you have any tips for first-time blog writers? I’d definitely appreciate it.

  15. Thanks for your advice on this blog. A single thing I wish to say is that purchasing electronics items on the Internet is not new. In truth, in the past decades alone, the market for online electronics has grown a great deal. Today, you’ll find practically any specific electronic gizmo and tools on the Internet, from cameras in addition to camcorders to computer parts and game playing consoles.

  16. Amazing blog! Do you have any recommendations for aspiring writers? I’m hoping to start my own website soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely overwhelmed .. Any suggestions? Bless you!

  17. Thanks for enabling me to obtain new suggestions about personal computers. I also possess the belief that one of the best ways to maintain your laptop in prime condition has been a hard plastic case, or shell, that suits over the top of the computer. A majority of these protective gear will be model specific since they are made to fit perfectly across the natural casing. You can buy all of them directly from owner, or via third party places if they are readily available for your notebook computer, however only a few laptop could have a shell on the market. Yet again, thanks for your suggestions.

  18. Good web site! I truly love how it is simple on my eyes and the data are well written. I’m wondering how I could be notified whenever a new post has been made. I have subscribed to your RSS feed which must do the trick! Have a nice day!

  19. One thing is that one of the most frequent incentives for applying your cards is a cash-back or maybe rebate present. Generally, you’ll get 1-5 back on various acquisitions. Depending on the card, you may get 1 returning on most purchases, and 5 in return on acquisitions made on convenience stores, gas stations, grocery stores and ‘member merchants’.

  20. buy-aqualyx-online usa uk
    aquashine-btx-1x2ml usa uk
    belotero-balance-1x1ml usa uk
    belotero-lips-contour-1×0-6ml usa uk
    juvederm-ultra-smile-for-sale usa uk
    juvederm-volux usa uk
    buy-profhilo-h-l-online usa uk
    what-is-in-radiesse-lidocaine usa uk
    restylane-1x1ml uk usa
    restylane-lidocaine-1×0-5ml uk usa
    buy-revolax-fine-onine uk usa
    teosyal-27g-deep-lines-puresense-2x1ml uk usa
    dermal-fillers usa
    buy-allergan-botox-online-without-prescription uk usa
    azzalure-2×125-iu uk usa
    dysport-for-sale uk usa
    cobalin-h-hydroxocobalamin-5x1ml uk usa
    xeomin-for-sale
    how-does-neurobloc-work
    buy-botulinums-diluent-online uk usa
    bocouture-1×100-units
    <a href=" restylane usa uk
    revanesse usa uk
    revolax usa uk
    buy-juvederm-online usa uk
    radiesse usa uk
    radiesse usa uk
    buy-restylane-online usa uk
    acdc-strain-online usa uk
    buy-bc-big-bud-online uk usa
    buy-nyc-diesel-cannabis-strain-online uk usa
    roor-glass-ashtray uk usa
    buy concentrates online uk usa
    mescalin-or-peyote usa
    blueberry-marijuana-strain uk usa
    grape-god uk usa
    durban-poison-cannabis-strain uk usa
    buy-purple-haze-online uk usa
    g13-haze
    buy-cookies-carts-online usa uk
    buy-tko-edibles-online uk usa
    buy sun-rockss online
    buy1035mg-northern-lights-premium-cannabis-oil-cart usa uk au
    buy-purple-haze-online uk usa
    buytko-edibles-brownie online uk usa
    buy-gorrilla-glue uk usa
    buy-550mg-blue-dream-premium-cannabis-oil-cart uk usa
    buy-bloom-vape-maui-waui uk usa
    buy-cookies-high-flyer-premium-cartridge-snowmanuk usa
    CTe8a2VS6Qg1EA0
    white-runtz-for-sale-near-me usa uk au
    berry-pie-for-sale usa uk
    420buds2go
    “buy carts and edibles online
    buy-exotic-carts-online
    buy brass-knuckles online
    buy-4-aco-dmt-online usa uk au
    buy-purple-haze-online uk usa
    buytko-edibles-brownie online uk usa
    albino-magic-mushroom uk usa
    buy-xanax-online uk usa
    buy-psychedelics-online uk usa
    morel-mushrooms-for-sale usa
    lsd-tabs-for-sale uk usa
    white-runtz-for-sale-near-me usa uk au
    berry-pie-for-sale usa uk
    420buds2go
    “buy carts and edibles online
    buy-exotic-carts-online
    buy brass-knuckles online

  21. Greetings! I’ve been reading your blog for a long time now and finally got the bravery to go ahead and give you a shout out from Kingwood Tx! Just wanted to say keep up the fantastic work!

  22. Howdy! I just want to give a huge thumbs up for the good information you will have right here on this post. I will likely be coming back to your weblog for extra soon.

  23. buy-aqualyx-online usa uk
    aquashine-btx-1x2ml usa uk
    belotero-balance-1x1ml usa uk
    belotero-lips-contour-1×0-6ml usa uk
    juvederm-ultra-smile-for-sale usa uk
    juvederm-volux usa uk
    buy-profhilo-h-l-online usa uk
    what-is-in-radiesse-lidocaine usa uk
    restylane-1x1ml uk usa
    restylane-lidocaine-1×0-5ml uk usa
    buy-revolax-fine-onine uk usa
    teosyal-27g-deep-lines-puresense-2x1ml uk usa
    dermal-fillers usa
    buy-allergan-botox-online-without-prescription uk usa
    azzalure-2×125-iu uk usa
    dysport-for-sale uk usa
    cobalin-h-hydroxocobalamin-5x1ml uk usa
    xeomin-for-sale
    how-does-neurobloc-work
    buy-botulinums-diluent-online uk usa
    bocouture-1×100-units
    <a href=" restylane usa uk
    revanesse usa uk
    revolax usa uk
    buy-juvederm-online usa uk
    radiesse usa uk
    radiesse usa uk
    buy-restylane-online usa uk
    acdc-strain-online usa uk
    buy-bc-big-bud-online uk usa
    buy-nyc-diesel-cannabis-strain-online uk usa
    roor-glass-ashtray uk usa
    buy concentrates online uk usa
    mescalin-or-peyote usa
    blueberry-marijuana-strain uk usa
    grape-god uk usa
    durban-poison-cannabis-strain uk usa
    buy-purple-haze-online uk usa
    g13-haze
    buy-cookies-carts-online usa uk
    buy-tko-edibles-online uk usa
    buy sun-rockss online
    buy1035mg-northern-lights-premium-cannabis-oil-cart usa uk au
    buy-purple-haze-online uk usa
    buytko-edibles-brownie online uk usa
    buy-gorrilla-glue uk usa
    buy-550mg-blue-dream-premium-cannabis-oil-cart uk usa
    buy-bloom-vape-maui-waui uk usa
    buy-cookies-high-flyer-premium-cartridge-snowmanuk usa
    CTe8a2VS6Qg1EA0
    white-runtz-for-sale-near-me usa uk au
    berry-pie-for-sale usa uk
    420buds2go
    “buy carts and edibles online
    buy-exotic-carts-online
    buy brass-knuckles online
    buy-4-aco-dmt-online usa uk au
    buy-purple-haze-online uk usa
    buytko-edibles-brownie online uk usa
    albino-magic-mushroom uk usa
    buy-xanax-online uk usa
    buy-psychedelics-online uk usa
    morel-mushrooms-for-sale usa
    lsd-tabs-for-sale uk usa
    white-runtz-for-sale-near-me usa uk au
    berry-pie-for-sale usa uk
    420buds2go
    “buy carts and edibles online
    buy-exotic-carts-online
    buy brass-knuckles online

  24. I抦 impressed, I must say. Really hardly ever do I encounter a blog that抯 each educative and entertaining, and let me tell you, you may have hit the nail on the head. Your thought is excellent; the difficulty is one thing that not sufficient people are speaking intelligently about. I am very glad that I stumbled across this in my search for one thing referring to this.

  25. Another thing I have noticed is that for many people, a bad credit score is the result of circumstances outside of their control. For example they may happen to be saddled with an illness and as a consequence they have substantial bills for collections. Maybe it’s due to a work loss or perhaps the inability to work. Sometimes divorce or separation can really send the finances in the undesired direction. Thanks sharing your thinking on this site.

  26. hey there and thank you on your information ?I抳e definitely picked up something new from right here. I did then again expertise several technical points the usage of this website, since I experienced to reload the website lots of occasions prior to I may just get it to load correctly. I were brooding about if your web host is OK? Not that I am complaining, but sluggish loading cases occasions will sometimes have an effect on your placement in google and can harm your quality rating if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Anyway I抦 adding this RSS to my email and could look out for much extra of your respective interesting content. Make sure you replace this once more very soon..

  27. Hey I am so grateful I found your website, I really found you by error, while I was browsing on Askjeeve for something else, Nonetheless I am here now and would just like to say many thanks for a marvelous post and a all round thrilling blog (I also love the theme/design), I don抰 have time to read through it all at the minute but I have bookmarked it and also included your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the superb work.

  28. I have realized that online degree is getting favorite because accomplishing your degree online has become a popular alternative for many people. Many people have never had a possibility to attend a regular college or university yet seek the improved earning possibilities and a better job that a Bachelor’s Degree provides. Still people might have a college degree in one discipline but would want to pursue some thing they now develop an interest in.

  29. One thing is the fact that one of the most widespread incentives for applying your card is a cash-back as well as rebate provision. Generally, you’ll receive 1-5 back on various purchases. Depending on the credit cards, you may get 1 again on most expenses, and 5 back again on acquisitions made in convenience stores, gasoline stations, grocery stores and also ‘member merchants’.

  30. WAXS
    Medical Cannabis wax
    Medical Cannabis wax, growing in popularity because of their heightened potency. Whether you’re looking for a way to relax after work or rapidly treat chronic pain, concentrates like wax are an excellent option. cannabis wax for sale

    In fact, cannabis wax is one of the most sought-after concentrates because the highest quality versions contain a THC content that’s equivalent to 15-20 joints! While there are plants available with a THC content of 30%, many wax concentrates have over 90% THC. cannabis wax for sale online

  31. Well, the article is in reality the finest on this worthw hile topic. I harmonise with your conclusions and also will certainly thirstily look forward to your approaching updates. Just saying thanks will certainly not simply just be enough, for the massive lucidity in your writing. I definitely will directly grab your rss feed to stay abreast of any kind of updates. Admirable work and much success in your business enterprize!

  32. The the next occasion I just read a blog, Lets hope so it doesnt disappoint me about this one. Get real, It was my solution to read, but I personally thought youd have some thing intriguing to say. All I hear is often a bunch of whining about something that you could fix in case you werent too busy searching for attention.

  33. Hey! This post couldn’t always be written much better! Examining this post reminds me of these area mate! He always stored talking about this. I’ll ahead this article to be able to your ex. Convinced he will have a very good go through. We appreciate you revealing!

  34. I have noticed that over the course of making a relationship with real estate managers, you’ll be able to get them to understand that, in most real estate financial transaction, a percentage is paid. Ultimately, FSBO sellers never “save” the percentage. Rather, they try to win the commission simply by doing the agent’s work. In doing this, they spend their money plus time to accomplish, as best they’re able to, the duties of an agent. Those jobs include displaying the home by way of marketing, offering the home to buyers, making a sense of buyer emergency in order to prompt an offer, scheduling home inspections, controlling qualification inspections with the loan provider, supervising maintenance, and aiding the closing.

  35. I have come across that right now, more and more people are increasingly being attracted to surveillance cameras and the industry of taking pictures. However, as a photographer, you must first devote so much time frame deciding which model of video camera to buy in addition to moving from store to store just so you could buy the lowest priced camera of the brand you have decided to pick. But it doesn’t end now there. You also have to contemplate whether you should buy a digital video camera extended warranty. Thx for the good suggestions I acquired from your weblog.

  36. The very heart of your writing while sounding agreeable initially, did not really work perfectly with me after some time. Someplace throughout the paragraphs you actually were able to make me a believer unfortunately just for a while. I nevertheless have got a problem with your jumps in logic and you might do well to help fill in those breaks. If you can accomplish that, I could certainly end up being amazed.

  37. Howdy would you mind sharing which blog platform you’re using? I’m looking to start my own blog in the near future but I’m having a difficult time choosing between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something completely unique. P.S Sorry for being off-topic but I had to ask!

  38. Hello there, I found your web site via Google even as searching for a related subject, your website came up, it appears great. I’ve bookmarked it in my google bookmarks.

  39. I’m not certaіn the place you’re getting your info, but good topic.
    I needs to spend a while finding out more or figuring out moгe.
    Thanks for great information I used to be looking for
    this information for my mission.

Leave a Reply

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