首先导入相应的jar包
http://files.cnblogs.com/java-pan/lib.rar
1.获取Json中的值(json-->java)
/**
* json转java
* @author evan_qb
*/
public static void jsonToJava(){
String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
//
JSONObject jsonObject = JSONObject.fromString(jsonStr);
String username = jsonObject.getString("username");
String password = jsonObject.getString("password");
System.out.println("json---> java\n username = " + username
+ "\npassword = " + password);
}
2.将java转换为json格式
/**
* java转json
*/
public static void javaToJson(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "张三");
jsonObject.put("password", "123456");
System.out.println("java--> json \n" + jsonObject.toString());
}
3.json转xml
/**
* json转xml
*/
public static void jsonToXml(){
String jsonStr = "{\"password\":\"\",\"username\":\"张三\"}";
//ͨ通过一个json格式的字符串构造一个JSONArray对象
JSONObject json = JSONObject.fromString(jsonStr);
XMLSerializer xmlSerializer = new XMLSerializer();
//设置转换的xml的根元素名称
xmlSerializer.setRootName("userInfo");
//设置每个元素是否显示type属性
xmlSerializer.setTypeHintsEnabled(false);
//把json对象转换为xml,默认的字符编码是UTF-8
String xml = xmlSerializer.write(json,"UTF-8");
System.out.println("json-->xml:\n" + xml);
}
4.xml转json
/**
* xml转Json
*/
public static void xmlToJson(){
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<userInfo><password></password><username>张三</username></userInfo>";
JSON json = XMLSerializer.read(xml);
System.out.println("xml-->json:\n" + json);
}
5.javaBean转json
/**
* javaBean转json
*/
public static void javaBeanToJson(){
Student stu = new Student("张三",20,"123456");
JSONObject json = JSONObject.fromBean(stu);
System.out.println("javaBean-->json:\n" + json);
}
6.javaBean转xml
/**
* javaBean转xml
*/
public static void javaBeanToXml(){
Student stu = new Student("张三",20,"123456");
JSONObject json = JSONObject.fromBean(stu);
XMLSerializer xmlSerializer = new XMLSerializer();
String xml = xmlSerializer.write(json,"UTF-8");
System.out.println("javaBean-->xml:" + xml);
}