欢迎光临
一个有态度、有温度的分享型博客

使用google gson对json字符串和Java对象进行转换

使用google gson对json字符串和Java对象进行转换

java对象转换为json字符串

转换代码


/** * @author https://www.rxblog.xyz */ public class JavaToJsonDemo { public static void main(String[] args) { Person jack = new Person(); jack.setName("Jack"); jack.setAge(1); Person michael = new Person(); michael.setName("Michael"); jack.setAge(5); Gson gson = new Gson(); //示例1 System.out.println("================示例1=========="); System.out.println(gson.toJson(jack)); Company myCompany = new Company(); myCompany.setAddress("山东济南"); List<Person> personList = new ArrayList<>(); personList.add(jack); personList.add(michael); myCompany.setEmployees(personList); //示例2 System.out.println("================示例2=========="); System.out.println(gson.toJson(personList)); //示例3 System.out.println("================示例3=========="); System.out.println(gson.toJson(myCompany)); } }

输出结果

================示例1==========
{"name":"Jack","age":5}
================示例2==========
[{"name":"Jack","age":5},{"name":"Michael","age":0}]
================示例3==========
{"address":"山东济南","employees":[{"name":"Jack","age":5},{"name":"Michael","age":0}]}

json字符串转换为Java对象

  • 示例1
{"name":"Michael","age":2}

转换代码:

Gson gson = new Gson();
Person michael = gson.fromJson("{\"name\":\"Michael\",\"age\":2}",Person.class);
System.out.println(michael.getAge());
  • 示例2
{"status":"0","msg":"","data":[{"GMSFHM":"3890871234","XM":"王**","XB":"男","MZ":"汉","CSRQ":"1993","CSD_GJHDQ":"出生地国家(地区)","CSD_SSXQ":"出生地省市县(区)","CSD_QHNXXDZ":出生地详址,"JG_GJHDQ":"籍贯国家(地区)","JG_SSXQ":"籍贯省市县(区)","WHCD":"文化程度","HYZK":"婚姻状况","BYZK":"兵役状况","SG":"177","ZY":"职业","FWCS":"服务处所","HJD_SSXQ":"户籍地址省市县(区)","HJD_QHNXXDZ":"户籍地址详址","ZXBZ":"注销标识","PCS":"所属公安机关名称"}]}

转换代码:

String jsonStr = "{\"status\":\"0\",\"msg\":\"\",\"data\":[{\"GMSFHM\":\"3890871234\",\"XM\":\"王**\",\"XB\":\"男\",\"MZ\":\"汉\",\"CSRQ\":\"1993\",\"CSD_GJHDQ\":\"出生地国家(地区)\",\"CSD_SSXQ\":\"出生地省市县(区)\",\"CSD_QHNXXDZ\":出生地详址,\"JG_GJHDQ\":\"籍贯国家(地区)\",\"JG_SSXQ\":\"籍贯省市县(区)\",\"WHCD\":\"文化程度\",\"HYZK\":\"婚姻状况\",\"BYZK\":\"兵役状况\",\"SG\":\"177\",\"ZY\":\"职业\",\"FWCS\":\"服务处所\",\"HJD_SSXQ\":\"户籍地址省市县(区)\",\"HJD_QHNXXDZ\":\"户籍地址详址\",\"ZXBZ\":\"注销标识\",\"PCS\":\"所属公安机关名称\"}]}";
HjxxResult result = gson.fromJson(jsonStr, HjxxResult.class);
if ("0".equals(result.getStatus())) {
    List<Hjxx> hjxxList = result.getData();
    //入库
    if (hjxxList != null && hjxxList.size() > 0) {
        for (Hjxx hjxx : hjxxList) {
            System.out.println(hjxx.getMZ());
        }
    }
}

示例代码

https://github.com/cobcmw/gsonDemos

参考:

  1. https://my.oschina.net/itblog/blog/204120;
  2. http://qingkechina.blog.51cto.com/5552198/1290500;
  3. http://wl9739.github.io/2017/01/13/Gson-%E4%B8%AD%E6%96%87%E6%8C%87%E5%8D%97/;
  4. https://blog.csdn.net/fang323619/article/details/42874503 ;

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址