当前位置: 移动技术网 > IT编程>开发语言>Java > java中实体类和JSON对象之间相互转化

java中实体类和JSON对象之间相互转化

2019年07月22日  | 移动技术网IT编程  | 我要评论

在需要用到json对象封装数据的时候,往往会写很多代码,也有很多复制粘贴,为了用pojo的思想我们可以装json转化为实体对象进行操作

package myutil;
 
import java.io.ioexception;
 
import myproject.student;
import myproject.studentlist;
 
import org.codehaus.jackson.map.objectmapper;
import org.json.jsonarray;
import org.json.jsonexception;
import org.json.jsonobject;
/**
 * 实体类和json对象之间相互转化(依赖包jackson-all-1.7.6.jar、jsoup-1.5.2.jar)
 * @author wck
 *
 */
public class jsonutil {
  /**
   * 将json转化为实体pojo
   * @param jsonstr
   * @param obj
   * @return
   */
  public static<t> object jsontoobj(string jsonstr,class<t> obj) {
    t t = null;
    try {
      objectmapper objectmapper = new objectmapper();
      t = objectmapper.readvalue(jsonstr,
          obj);
    } catch (exception e) {
      e.printstacktrace();
    }
    return t;
  }
  /**
   * 将实体pojo转化为json
   * @param obj
   * @return
   * @throws jsonexception
   * @throws ioexception
   */
  public static<t> jsonobject 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 new jsonobject(jsonstr);
  }
  public static void main(string[] args) throws jsonexception, ioexception {
    jsonobject obj = null;
    obj = new jsonobject();
    obj.put("name", "213");
    obj.put("age", 27);
    jsonarray array = new jsonarray();
    array.put(obj);
    obj = new jsonobject();
    obj.put("name", "214");
    obj.put("age", 28);
    array.put(obj);
    student stu = (student) jsontoobj(obj.tostring(), student.class);
    jsonobject objlist = new jsonobject();
    objlist.put("student", array);
    system.out.println("objlist:"+objlist);
    studentlist stulist = (studentlist) jsontoobj(objlist.tostring(), studentlist.class);
    system.out.println("student:"+stu);
    system.out.println("stulist:"+stulist);
    system.out.println("#####################################");
    jsonobject getobj = objecttojson(stu);
    system.out.println(getobj);
  }
}

以上所述就是本文的全部内容了,希望大家能够喜欢。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网