Two methods for entity class to Json in java

  • 2020-05-27 05:40:31
  • OfStack

First declare the required jar package:

ezmorph-1.0.6.jar jackson-all-1.7.6.jar jsoup-1.5.2.jar

1. Create an entity class 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;
  }

}

2. Entity class conversion to 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();
  }

  //  The main function 
  public static void main(String[] args) {

    Emp emp=new Emp();
    emp.setId(1);
    emp.setName(" zhang 3");
    emp.setGender(" male ");
    emp.setDptNo(001);
    emp.setDuty(" clerk ");
    
    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 {
  
  //  The main function 
  public static void main(String[] args) {

    Emp emp=new Emp();
    emp.setId(1);
    emp.setName(" zhang 3");
    emp.setGender(" male ");
    emp.setDptNo(001);
    emp.setDuty(" clerk ");
    
    JSONObject jsonObject = JSONObject.fromObject(emp);
    
    System.out.println(jsonObject);
    
  }

}


Related articles: