首先申明所需jar包:
ezmorph-1.0.
jackson-all-1.7.
jsoup-1.5.
一、创建一个实体类Emp.
package ;
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) {
= id;
}
public String getName() {
return name;
}
public void setName(String name) {
= name;
}
public Integer getDptNo() {
return dptNo;
}
public void setDptNo(Integer dptNo) {
= dptNo;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
= gender;
}
public String getDuty() {
return duty;
}
public void setDuty(String duty) {
= duty;
}
}
二、实体类转换为Json
(1)
import ;
import ;
import .;
import ;
import ;
public class MainTest {
public static String objectToJson(T obj) throws JSONException, IOException {
ObjectMapper mapper = new ObjectMapper();
// Convert object to JSON string
String jsonStr = "";
try {
jsonStr = (obj);
} catch (IOException e) {
throw e;
}
return (obj).toString();
}
// 主函数
public static void main(String[] args) {
Emp emp=new Emp();
(1);
("张三");
("男");
(001);
("职员");
String jsonStr="";
try {
jsonStr=objectToJson(emp);
} catch (JSONException e) {
();
} catch (IOException e) {
();
}
(jsonStr);
}
}
(2)
import ;
import ;
public class MainTest {
// 主函数
public static void main(String[] args) {
Emp emp=new Emp();
(1);
("张三");
("男");
(001);
("职员");
JSONObject jsonObject = (emp);
(jsonObject);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我。