首先申明所需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); }}以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選