你的位置:首页 > Java教程

[Java教程]实体类转Json的2种方法

首先申明所需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 }