java中實(shí)體類轉(zhuǎn)Json的2種方法
首先申明所需jar包:
- ezmorph-1.0.6.jar
- jackson-all-1.7.6.jar
- jsoup-1.5.2.jar
一、創(chuàng)建一個(gè)實(shí)體類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;
}
}
二、實(shí)體類轉(zhuǎn)換為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();
}
// 主函數(shù)
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 {
// 主函數(shù)
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);
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決Maven打包只有幾十K,運(yùn)行報(bào)錯(cuò)no main manifest attribute
這篇文章主要介紹了解決Maven打包只有幾十K,運(yùn)行報(bào)錯(cuò)no main manifest attribute問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
Spring中BeanFactory和ApplicationContext的作用和區(qū)別(推薦)
這篇文章主要介紹了Spring中BeanFactory和ApplicationContext的作用和區(qū)別,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09
SpringBoot自動(dòng)配置特點(diǎn)與原理詳細(xì)分析
這篇文章主要介紹了SpringBoot自動(dòng)配置原理分析,SpringBoot是我們經(jīng)常使用的框架,那么你能不能針對SpringBoot實(shí)現(xiàn)自動(dòng)配置做一個(gè)詳細(xì)的介紹。如果可以的話,能不能畫一下實(shí)現(xiàn)自動(dòng)配置的流程圖。牽扯到哪些關(guān)鍵類,以及哪些關(guān)鍵點(diǎn)2022-08-08
必須掌握的十個(gè)Lambda表達(dá)式簡化代碼提高生產(chǎn)力
這篇文章主要為大家介紹了必須掌握的十個(gè)Lambda表達(dá)式來簡化代碼提高生產(chǎn)力,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
SpringBoot 動(dòng)態(tài)定時(shí)器的使用方法
這篇文章主要介紹了SpringBoot 動(dòng)態(tài)定時(shí)器的使用方法,非常不錯(cuò),具有一定的參考借鑒借鑒價(jià)值,需要的朋友可以參考下2018-05-05

