直接上代碼:
JSONObject的的使用需要導入json-lib-2.4-jdk15.jar包,下載地址:http://mvnrepository.com/artifact/net.sf.json-lib/json-lib/2.4;
1 package test; 2 3 import net.sf.json.JSONObject; 4 import testspringmysql.User; 5 6 public class TestClass 7 { 8 9 public static void main(String args[]) 10 { 11 //創建user對象 12 User user = new User(); 13 user.setAge(10); 14 user.setName("ceshi"); 15 16 //轉化成json對象 17 JSONObject jsonResult = JSONObject.fromObject(user); 18 //輸出 19 System.out.println(jsonResult); 20 21 } 22 }
user類
package testspringmysql; public class User { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
結果: