JavaBean转JSON

黄弘深
2023-12-01

JavaBean转JSON

在CSDN中看到了好几个类型的转换方式,导入不同的jar包,可执行的效果不一样,博主只是想把javabean类型转化为json类型数据,以下为几种不同的jar包的使用经历:

一.使用net.sf.json.*下的类(jar包是json-lib-x.x.jar)

就是网上普遍使用的需要添加的6个jar包。
方法是:JSONObject obj = JSONObject.fromObject(map);,博主试了几次,每次都被提示要把bean转化为Map类型。

2.使用import com.google.gson.Gson

在pom文件中插入:

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

需要注意的是,此时需要Import的不是org.json.JSONObject.*类,我、而是com.google.gson.Gson
使用方法:

  Admin admin= new Admin();
  admin=adminService.findAdminByAdminId(id);
  Gson json=new Gson();
  String str=json.toJson(admin);// 传入Bean类型,str就是结果

3.使用所谓的json.jar包

使用方式:

JSONObject obj=new JSONObject(admiin);
String str=obj.toString();

但是博主在网上搜了半天,也没有搜到这个jar包,不知道是不是理解错了还是怎么样。

综合测试的结果,博主最终使用的是方法二。

 类似资料: