概述
作为 面向对象
开发的程序员,每天的业务代码会遇到大量的 Json
处理。本文从最常见的几个类库 gson
, fastjson
, jackson
进行基本操作, 仅作记录。
基础准备
首先创建java对象用于测试
角色
1 2 3 4 5 6 7 8 9 10 11 12 13 @Data @NoArgsConstructor @AllArgsConstructor public class Role { private String roleName; }
这里我们创建一个复合嵌套对象user
1 2 3 4 5 6 7 8 9 10 11 @Data public class User { private String userName; private List<Role> roles; }
用户组
1 2 3 4 5 6 7 8 9 10 11 12 @Data public class UserGroup implements Serializable { private String groupName; private Map<String, User> idNumber; }
菜单
1 2 3 4 5 6 7 8 9 10 11 12 13 @Data @AllArgsConstructor public class Menu { @SerializedName("menu_name") private String menuName; }
部门
1 2 3 4 5 6 7 8 9 10 @Data @AllArgsConstructor public class Dept { private String deptName; }
类型适配器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class DeptAdapter implements JsonSerializer <Dept > { @Override public JsonElement serialize (Dept dept, Type type, JsonSerializationContext jsonSerializationContext) { JsonObject deptObject = new JsonObject(); deptObject.addProperty("dept_name" , dept.getDeptName()); return deptObject; } }
Gson
maven依赖
1 2 3 4 <dependency > <groupId > com.google.code.gson</groupId > <artifactId > gson</artifactId > </dependency >
单元测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 class GsonTest { @Test void toJson () { Role role1 = new Role("系统管理员" ); Role role2 = new Role("普通管理员" ); User user = new User(); user.setUserName("admin" ); user.setRoles(Arrays.asList(role1, role2)); String json = new Gson().toJson(user); System.out.println(json); } @Test void toJson2 () { Role role1 = new Role("系统管理员" ); Role role2 = new Role("普通管理员" ); User user = new User(); user.setUserName("admin" ); user.setRoles(Arrays.asList(role1, role2)); String json = new GsonBuilder().create().toJson(user); System.out.println(json); } @Test void fromJson () { String json = "{\"userName\":\"admin\",\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]}" ; User user = new Gson().fromJson(json, User.class); System.out.println(user); } @Test void createJsonObject () { JsonObject role = new JsonObject(); role.addProperty("roleName" , "超级管理员" ); JsonObject user = new JsonObject(); user.addProperty("userName" , "admin" ); user.add("roles" , role); String username = user.get("userName" ).getAsString(); System.out.println(username); System.out.println(user); } @Test void json2Object () { String json = "{\"userName\":\"admin\",\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]}" ; JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject(); String userName = jsonObject.get("userName" ).getAsString(); System.out.println(userName); } @Test void list2Json () { Role role1 = new Role("系统管理员" ); Role role2 = new Role("普通管理员" ); String json = new Gson().toJson(Arrays.asList(role1, role2)); System.out.println(json); } @Test void json2List () { String json = "[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]" ; List<Role> roles = new Gson().fromJson(json, new TypeToken<List<Role>>() {}.getType()); System.out.println(roles); } @Test void json2Array () { String json = "[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]" ; JsonArray jsonArray = JsonParser.parseString(json).getAsJsonArray(); System.out.println(jsonArray); } @Test void map2Json () { HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("userName" , "admin" ); String json = new Gson().toJson(hashMap); System.out.println(json); } @Test void json2Map () { String json = "{\"userName\":\"admin\"}" ; HashMap hashMap = new Gson().fromJson(json, new TypeToken<HashMap<String, String>>() {}.getType()); System.out.println(hashMap.get("userName" )); } @Test void setFieldNamingPolicy1 () { Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY) .create(); Role role = new Role("超级管理员" ); String json = gson.toJson(role); System.out.println(json); } @Test void setFieldNamingPolicy2 () { Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) .create(); Role role = new Role("超级管理员" ); String json = gson.toJson(role); System.out.println(json); } @Test void setFieldNamingPolicy3 () { Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES) .create(); Role role = new Role("超级管理员" ); String json = gson.toJson(role); System.out.println(json); } @Test void setFieldNamingPolicy4 () { Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); Role role = new Role("超级管理员" ); String json = gson.toJson(role); System.out.println(json); } @Test void setFieldNamingPolicy5 () { Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) .create(); Role role = new Role("超级管理员" ); String json = gson.toJson(role); System.out.println(json); } @Test void setFieldNamingPolicy6 () { Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS) .create(); Role role = new Role("超级管理员" ); String json = gson.toJson(role); System.out.println(json); } @Test void serializedName () { Menu menu = new Menu("系统管理" ); String json = new Gson().toJson(menu); System.out.println(json); } @Test void adapter () { Gson gson = new GsonBuilder() .registerTypeAdapter(Dept.class, new DeptAdapter()) .create(); Dept dept = new Dept("产品研发部" ); String json = gson.toJson(dept); System.out.println(json); } }
FastJson
maven依赖
1 2 3 4 5 <dependency > <groupId > com.alibaba</groupId > <artifactId > fastjson</artifactId > <version > 1.2.68</version > </dependency >
单元测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 public class FastJsonTest { @Test void toJson () { Role role1 = new Role("系统管理员" ); Role role2 = new Role("普通管理员" ); User user = new User(); user.setUserName("admin" ); user.setRoles(Arrays.asList(role1, role2)); String userJson = JSON.toJSONString(user); System.out.println(userJson); } @Test void jsonParse () { String json = "{\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}],\"userName\":\"admin\"}" ; JSONObject jsonObject = JSON.parseObject(json); System.out.println(jsonObject.getString("userName" )); System.out.println(jsonObject); } @Test void list2Json () { Role role1 = new Role("系统管理员" ); Role role2 = new Role("普通管理员" ); String jsonString = JSON.toJSONString(Arrays.asList(role1, role2)); System.out.println(jsonString); } @Test void json2List () { String json = "[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]" ; JSONArray jsonArray = JSON.parseArray(json); System.out.println(jsonArray); } @Test void json2List2 () { String json = "[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]" ; List<Role> users = JSON.parseArray(json, Role.class); System.out.println(users); } @Test void json2Bean () { String json = "{\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}],\"userName\":\"admin\"}" ; User user = JSON.parseObject(json, User.class); System.out.println(user); } @Test void json2Bean2 () { String json = "{\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}],\"userName\":\"admin\"}" ; User user = JSON.parseObject(json, new TypeReference<User>(){}); System.out.println(user); } @Test void map2Json () { HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("userName" , "admin" ); String jsonString = JSON.toJSONString(hashMap); System.out.println(jsonString); } @Test void json2Map () { String json = "{\"userName\":\"admin\"}" ; Map<String, String> map = (Map<String, String>) JSON.parse(json); System.out.println(map.get("userName" )); } @Test void json2Map2 () { String json = "{\"userName\":\"admin\"}" ; Map map = JSON.parseObject(json); System.out.println(map); } @Test void obj2Json () { Role role1 = new Role("系统管理员" ); Role role2 = new Role("普通管理员" ); User user = new User(); user.setUserName("admin" ); user.setRoles(Arrays.asList(role1, role2)); HashMap<String, User> map = new HashMap<>(); map.put("001" , user); UserGroup userGroup = new UserGroup(); userGroup.setGroupName("分组1" ); userGroup.setIdNumber(map); String jsonString = JSON.toJSONString(userGroup); System.out.println(jsonString); } @Test void json2Obj () { String json = "{\"groupName\":\"分组1\",\"idNumber\":{\"001\":{\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}],\"userName\":\"admin\"}}}" ; UserGroup userGroup = JSON.parseObject(json, UserGroup.class); System.out.println(userGroup); } }
Jackson
单元测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 public class JacksonTest { @Test void Obj2Json () throws JsonProcessingException { Role role1 = new Role("系统管理员" ); Role role2 = new Role("普通管理员" ); User user = new User(); user.setUserName("admin" ); user.setRoles(Arrays.asList(role1, role2)); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(user); System.out.println(json); } @Test void json2Obj () throws JsonProcessingException { String json = "{\"userName\":\"admin\",\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]}" ; ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(json, User.class); System.out.println(user); } @Test void json2Obj2 () throws JsonProcessingException { String json = "{\"userName\":\"admin\",\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]}" ; ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(json); String userName = jsonNode.get("userName" ).asText(); System.out.println(userName); } @Test void list2Json () throws JsonProcessingException { Role role1 = new Role("系统管理员" ); Role role2 = new Role("普通管理员" ); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(Arrays.asList(role1, role2)); System.out.println(json); } @Test void json2List () throws JsonProcessingException { String json = "[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]" ; ObjectMapper mapper = new ObjectMapper(); List<Role> roles = mapper.readValue(json, new TypeReference<List<Role>>() { }); System.out.println(roles); } }
配置
1 @JsonInclude(JsonInclude.Include.NON_NULL)
1 2 3 4 5 6 7 8 9 @JsonProperty("NAME") private String name;
1 2 3 4 5 @JsonAlias("age_alias") private Integer age;
1 2 3 4 5 6 7 8 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime date;
1 2 3 4 5 6 7 ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false ); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 package cn.idea360.jpa;import com.fasterxml.jackson.annotation.JsonTypeInfo;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;import lombok.Data;import lombok.extern.slf4j.Slf4j;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import java.io.Serializable;@Slf4j class JsonTest { @Data public static class Student implements Serializable { private String name; } @Data public static class Child implements Serializable { private String name; } @Data public static class Father implements Serializable { private Child[] children; } @Data public static class Teacher implements Serializable { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class") private Student student; @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class") private Child[] children; } private Student student; private Father father; private Teacher teacher; @BeforeEach void init () { student = new Student(); student.setName("admin" ); Child child = new Child(); child.setName("张三" ); father = new Father(); father.setChildren(new Child[]{child}); teacher = new Teacher(); teacher.setStudent(student); teacher.setChildren(new Child[]{child}); } @Test void toJson () throws Exception { ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(student); log.info(json); } @Test void toJsonWithClass1 () throws Exception { ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(teacher); log.info(json); } @Test void toJsonWithClass2 () throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false ); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE).setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); String json = objectMapper.writeValueAsString(father); log.info(json); Father father = objectMapper.readValue(json, Father.class); log.info(String.valueOf(father)); } }
最后
本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】,您的支持是我写作的最大动力。
参考