首先申明所需 JAR 包 :
一、创建一个实体类 Emp.
paket com.hyx.entity; kelas publik emp {private integer id; nama string pribadi; Private Integer DPTNO; Jenis kelamin string pribadi; tugas string pribadi; Integer publik getId () {return id; } public void setid (integer id) {this.id = id; } public string getName () {return name; } public void setName (name string) {this.name = name; } public integer getDptNo () {return dptno; } public void setDptno (integer dptno) {this.dptno = dptno; } public string getGender () {return gender; } public void setGender (string gender) {this.gender = gender; } public String getDuty () {return Duty; } public void setDuty (string duty) {this.duty = Duty; }}二、实体类转换为 json
(1)
Impor java.io.ioException; impor net.sf.json.jsonobject; impor org.apache.struts2.json.jSonexception; org.codehaus.jackson.map.objectmapper; Impor com.hyx.entity.emp; class classest {public static <t> string {public classccepteon (TROWSEPCEPCEncEncepion (TROWSCEPCEnDEnDEnD) ObjectMapper mapper = new ObjectMapper (); // Konversi objek ke string json string jsonstr = ""; coba {jsonstr = mapper.writevalueAsstring (obj); } catch (ioException e) {throw e; } return jsonobject.fromObject (obj) .toString (); } // 主函数 public static void main (string [] args) {emp emp = baru emp (); emp.setid (1); emp.setname ("张三"); emp.setgender ("男"); emp.setdptno (001); emp.setDuty ("职员"); String jsonstr = ""; coba {jsonstr = objectToJson (emp); } catch (jsonexception e) {e.printstacktrace (); } catch (ioException e) {e.printstacktrace (); } System.out.println (jsonstr); }} (2)
impor net.sf.json.jsonobject; import com.hyx.entity.emp; kelas publik Maintest {// 主函数 public static void main (string [] args) {emp emp = emp emp (baru); emp.setid (1); emp.setname ("张三"); emp.setgender ("男"); emp.setdptno (001); emp.setDuty ("职员"); JsonObject jsonObject = jsonobject.fromObject (emp); System.out.println (jsonObject); }}以上就是本文的全部内容 , 希望对大家的学习有所帮助 , 也希望大家多多支持武林网。