数据库json字段映射到对象,springboot json映射成实体

2022年 10月 20日 发表评论
腾讯云正在大促:点击直达 阿里云超级红包:点击领取
免费/便宜/高性价比服务器汇总入口(已更新):点击这里了解
前言

之前解析 json 格式一直使用jsonObject,jsonArray,虽然使用起来还算可以,但后来发现可以使用实体类映射,貌似也还可以。而且代码复用性比较好。

使用工具

idea,com.alibaba.fastjson.JSON

json数据 {"website":"chinamobilesh","create_time":157360,"basic_version":{ "user_gender": "男", "user_searched_history_by_orgs": [ { "org_self": true, "searched_date": "2017-11-07", "searched_org": "其他" }, { "org_self": false, "searched_date": "2017-07-08", "searched_org": "线上消费分期" }, ] }}

String 格式

String data = "{"website":"chinamobilesh", "create_time":157360, "basic_version":{"user_gender": "男","user_searched_history_by_orgs": [{"org_self": true,"searched_date": "2017-11-07","searched_org": "其他"},{"org_self": false,"searched_date": "2017-07-08","searched_org": "线上消费分期"}]}}"; pojo实体类

可以参考 json在线解析

package com.pojo;import java.util.List;public class Root { private String website; private int createTime; private BasicVersion basicVersion; //省略getter/setter... public static class UserSearchedHistoryByOrgs { private boolean orgSelf; private String searchedDate; private String searchedOrg; //省略getter/setter... } public static class BasicVersion { private String userGender; private List<UserSearchedHistoryByOrgs> userSearchedHistoryByOrgs; //省略getter/setter...} 解析 Root root = JSON.parseObject(data,Root.class); BasicVersion basicVersion = root.getBasicVersion(); String userGender= basicVersion.getUserGender(); System.out.println(userGender);

结果:男

小咸鱼

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: