首先申明所需 pot 包 :
一、创建一个实体类 emp.
Package com.hyx.entity; classe publique Emp {ID entier privé; nom de chaîne privé; entier privé DPTNO; Gender de chaîne privée; service à cordes privées; public Integer getID () {return id; } public void setid (INGER ID) {this.id = id; } public String getName () {Nom de retour; } public void setName (string name) {this.name = name; } public entier getDPTNO () {return dptno; } public void setDptno (entier dptno) {this.dptno = dptno; } public String getgender () {return Gender; } public void setGender (String Sexe) {this.gender = genre; } public String getDuty () {return usine; } public void setDuty (String Duty) {this.duty = duty; }}二、实体类转换为 JSON
(1)
import 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 MainTest { public static<T> String objectToJson(T obj) throws JSONException, IOException { ObjectMapper Mappeur = new ObjectMapper (); // convertit objet en json string string jSontr = ""; essayez {jsonstr = mapper.writeValueAsString (obj); } catch (ioException e) {throw e; } return jsonObject.fromObject (obj) .toString (); } // 主函数 public static void main (String [] args) {emp emp = new emp (); Emp.setid (1); emp.setName ("张三"); Emp.setgender ("男"); Emp.setDptno (001); Emp.setDuty ("职员"); String jSontr = ""; essayez {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; classe publique se maintient {// 主函数 public static void main (String [] args) {empl = new emp (); Emp.setid (1); emp.setName ("张三"); Emp.setgender ("男"); Emp.setDptno (001); Emp.setDuty ("职员"); JSONObject JSONObject = JSONObject.FromObject (EMP); System.out.println (jsonObject); }}以上就是本文的全部内容 , 希望对大家的学习有所帮助 , 也希望大家多多支持武林网。