一个json格式转xml格式的java实现

源代码如下:

package com.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;

public class JSON2XML 
{
	private String mJSONSource;
	private String mXML;
	private String mPath = "C:\\Users\\i042416\\Desktop\\1.txt";
	private String mSavedXML = "C:\\Users\\i042416\\Desktop\\image.xml";
	private void getSource(String name) throws IOException
	{
			File file = new File(mPath);
			FileInputStream inputStream = new FileInputStream(file);
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			char[] buffer = new char[(int) file.length()];
			reader.read(buffer, 0, buffer.length);
			inputStream.close();
			mJSONSource = new String(buffer);
			//System.out.println("String length: " + mJSONSource);
	}
	
	public void run() throws IOException
	{
		getSource(mPath);
		parse();
		saveFile();
	}
	private void parse()
	{
		 JSON json = JSONSerializer.toJSON(mJSONSource);   
		 
		 XMLSerializer xmlSerializer = new XMLSerializer();   
		 xmlSerializer.setTypeHintsEnabled( false );       
		 xmlSerializer.setRootName("body" );      
		 mXML = xmlSerializer.write( json );      
		 System.out.println(mXML);      
  
	}
	
	private void saveFile()
	{
		try
		{
			FileOutputStream fos=new FileOutputStream(new File(mSavedXML));
		    OutputStreamWriter osw=new OutputStreamWriter(fos);
		    osw.write(mXML);
		    osw.flush();
		    osw.close();
		}
		catch(Exception ee)
		{
		     ee.printStackTrace();
		}
	}

	static public void main(String[] argc) throws IOException
	{
		JSON2XML tool = new JSON2XML();
		tool.run();
	}

}

你可能感兴趣的:(Java)