当前位置:主页 > 软件编程 > JAVA代码 >

java中实体类转Json的2种方法

时间:2020-12-06 10:05:23 | 栏目:JAVA代码 | 点击:

首先申明所需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);
    
  }

}

您可能感兴趣的文章:

相关文章