首先申明所需 Jar 包:
一、创建一个实体类 Emp.
pacote com.hyx.entity; public class EMP {private integer id; nome de string privado; Inteiro privado Dptno; gênero de cordas privadas; Dever de String Private; public integer getId () {return id; } public void SetId (ID inteiro) {this.id = id; } public string getName () {return name; } public void setName (nome da string) {this.name = name; } public integer getdptno () {return dptno; } public void Setdptno (Inteiro dptno) {this.dptno = dptno; } public string getGender () {return gênero; } public void setgender (string gênero) {this.gender = gênero; } public string getDuty () {return duty; } public void setDuty (string duty) {this.duty = duty; }}二、实体类转换为 JSON
(1)
importar java.io.ioException; importar net.sf.json.jsonObject; importar org.apache.struts2.json.jsonexception; importar org.codehaus.jackson.map.ObjectMapper; importar o objectjson (tumpjson. Mapper = new ObjectMapper (); // Converta o objeto em json string string jSonstr = ""; tente {jSonstr = mapper.WriteValuEasString (obj); } catch (ioexception e) {tiro e; } return jsonObject.FromObject (obj) .ToString (); } // 主函数 public static void main (string [] args) {empp emp = new emp (); Emp.setId (1); Emp.setName ("张三"); Emp.setGender ("男"); Emp.SetDPTNO (001); Emp.setDuty ("职员"); String jSonstr = ""; tente {jSonstr = objectTojson (EMP); } catch (jsonexception e) {e.printStackTrace (); } catch (ioexception e) {e.printStackTrace (); } System.out.println (JSonstr); }} (2)
importar net.sf.json.jsonObject; import com.hyx.entity.emp; public class Melhorest {// 主函数 public static void main (string [] args) {empp emp = new EMP (); Emp.setId (1); Emp.setName ("张三"); Emp.setGender ("男"); Emp.SetDPTNO (001); Emp.setDuty ("职员"); JsonObject jsonObject = jsonObject.FromObject (EMP); System.out.println (JsonObject); }}以上就是本文的全部内容 , 希望对大家的学习有所帮助 , 也希望大家多多支持武林网。