首先申明所需瓶包:
一、创建一个实体类EMP。
パッケージcom.hyx.entity; public class emp {private integer id;プライベート文字列名;プライベートインテガーdptno;プライベートストリングジェンダー;プライベートストリング義務; public Integer getId(){return id; } public void setid(integer id){this.id = id; } public string getname(){return name; } public void setName(string name){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)
java.io.ioexception; Import net.sf.json.jsonobject; import org.apache.struts2.json.jsonexception; Import org.codehaus.jackson.map.objectmapper; import com.hyx.entity.emp; public class emcestest {public static <t> string objectojson ObjectMapper mapper = new objectMapper(); //オブジェクトをjson文字列jsonstr = ""に変換します。 try {jsonstr = mapper.writevalueasstring(obj); } catch(ioexception e){shop e; } jsonobject.fromobject(obj).toString()を返します。 } // emp.setid(1); emp.setname( "张三"); emp.setgender( "男"); emp.setdptno(001); emp.setduty( "职员");文字列jsonstr = ""; try {jsonstr = objecttojson(emp); } catch(jsonexception e){e.printstacktrace(); } catch(ioexception e){e.printstacktrace(); } system.out.println(jsonstr); }} (2)
Import net.sf.json.jsonobject; import com.hyx.entity.emp; public class maintest {// emp.setid(1); emp.setname( "张三"); emp.setgender( "男"); emp.setdptno(001); emp.setduty( "职员"); jsonobject jsonobject = jsonobject.fromobject(emp); system.out.println(jsonobject); }}以上就是本文的全部内容、希望对大家的学习有所帮助、也希望大家多多支持武林网。