java中json操作xml和生成xml

java代码:
package com.syz;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import org.json.JSONObject;
import org.json.XML;

public class Test {  
    public static void main(String[] args) {  
        BufferedReader buffRed=null;  
        BufferedWriter buffWri=null;  

        try{  
            //将XML转换成JSON  
            String fileName1="json.xml";  
            buffRed=new BufferedReader(new FileReader(fileName1));  
            String tempStr;  
            StringBuffer xmlStrBuff=new StringBuffer();  
            while((tempStr=buffRed.readLine())!=null)  
            xmlStrBuff.append(tempStr);  
            JSONObject syz=XML.toJSONObject(xmlStrBuff.toString());
            System.out.println("syz="+syz.getInt("syz"));
            System.out.println("JSON str="+syz);  
           
            //将JSON转换成XML  
	        //String jsonStr="{Heros:{FBI:[{name:\"rose\",age:\"24\"},{name:\"jack\",age:\"25\"}],NBA:[{name:\"tom\",sex:\"man\"},{name:\"jack\",sex:\"women\"}]}};";  
            String jsonStr="{syz:2};";  
            String fileName2="json.xml";  
            buffWri=new BufferedWriter(new FileWriter(fileName2));  
            JSONObject jsonObj=new JSONObject(jsonStr);  
            buffWri.write("");  
            buffWri.newLine();  
            buffWri.write("");  
            buffWri.newLine();  
            buffWri.write(XML.toString(jsonObj));  
            buffWri.flush();  

            System.out.println("run end!");  
        }catch(Exception e){  
            e.printStackTrace();  
        }finally{  
            try{  
                if(buffRed!=null)  
                    buffRed.close();  
                if(buffWri!=null)  
                    buffWri.close();  
            }catch(Exception e){  
                e.printStackTrace();  
            }  
        }  
    }  
}
json.xml:


2

执行后控制台打印:

syz=2
JSON str={"syz":"2"}
run end!


json.jar包下载地址:http://download.csdn.net/detail/shiyuezhong/4574245


如果是在src\main\resources下的xml则通过以下方法取得:

String fileName1 = Thread.currentThread().getContextClassLoader().getResource("jsonxml.xml").getPath();  
 fileName1=fileName1.substring(1, fileName1.length());

你可能感兴趣的:(JAVA)