首先申明所需jar包:
ezmorph-1.0.6.jar
jackson-all-1.7.6.jar
jsoup-1.5.2.jar
一、創建一個實體類Emp.
1 package com.hyx.entity; 2 3 public class Emp { 4 private Integer id; 5 private String name; 6 private Integer dptNo; 7 private String gender; 8 private String duty; 9 10 public Integer getId() { 11 return id; 12 } 13 public void setId(Integer id) { 14 this.id = id; 15 } 16 public String getName() { 17 return name; 18 } 19 public void setName(String name) { 20 this.name = name; 21 } 22 public Integer getDptNo() { 23 return dptNo; 24 } 25 public void setDptNo(Integer dptNo) { 26 this.dptNo = dptNo; 27 } 28 public String getGender() { 29 return gender; 30 } 31 public void setGender(String gender) { 32 this.gender = gender; 33 } 34 public String getDuty() { 35 return duty; 36 } 37 public void setDuty(String duty) { 38 this.duty = duty; 39 } 40 41 }View Code
二、實體類轉換為Json
(1)
1 import java.io.IOException; 2 3 import net.sf.json.JSONObject; 4 5 import org.apache.struts2.json.JSONException; 6 import org.codehaus.jackson.map.ObjectMapper; 7 8 import com.hyx.entity.Emp; 9 10 11 12 public class MainTest { 13 14 public static<T> String objectToJson(T obj) throws JSONException, IOException { 15 ObjectMapper mapper = new ObjectMapper(); 16 // Convert object to JSON string 17 String jsonStr = ""; 18 try { 19 jsonStr = mapper.writeValueAsString(obj); 20 } catch (IOException e) { 21 throw e; 22 } 23 return JSONObject.fromObject(obj).toString(); 24 } 25 26 // 主函數 27 public static void main(String[] args) { 28 29 Emp emp=new Emp(); 30 emp.setId(1); 31 emp.setName("張三"); 32 emp.setGender("男"); 33 emp.setDptNo(001); 34 emp.setDuty("職員"); 35 36 String jsonStr=""; 37 try { 38 jsonStr=objectToJson(emp); 39 } catch (JSONException e) { 40 e.printStackTrace(); 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } 44 45 System.out.println(jsonStr); 46 47 48 } 49 50 }
(2)
1 import net.sf.json.JSONObject; 2 3 import com.hyx.entity.Emp; 4 5 6 7 public class MainTest { 8 9 // 主函數 10 public static void main(String[] args) { 11 12 Emp emp=new Emp(); 13 emp.setId(1); 14 emp.setName("張三"); 15 emp.setGender("男"); 16 emp.setDptNo(001); 17 emp.setDuty("職員"); 18 19 JSONObject jsonObject = JSONObject.fromObject(emp); 20 21 System.out.println(jsonObject); 22 23 } 24 25 }