首先申明所需jar包:
- ezmorph-1.0.6.jar
- jackson-all-1.7.6.jar
- jsoup-1.5.2.jar
一、创建一个实体类Emp.
package com.hyx.entity;public class Emp { private Integer id; private String name; private Integer dptNo; private String gender; private String duty; 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)
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 mapper = new ObjectMapper(); // Convert object to JSON string String jsonStr = ""; try { 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 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 { // 主函数 public static void main(String[] args) { Emp emp=new Emp(); emp.setId(1); emp.setName("张三"); emp.setGender("男"); emp.setDptNo(001); emp.setDuty("职员"); JSONObject jsonObject = JSONObject.fromObject(emp); System.out.println(jsonObject); }}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。