com.alibaba.fastjson.JSONObject是经常会用到的JSON工具包
//Java对象转换成String类型的JSON字符串
JSONObject.toJSONString(Java对象)//String类型的JSON字符串转换成Java对象
JSONObject.toJavaObject(JSON字符串,Java对象.class)//Json字符串转换成JSONObject对象
JSONObject.parseObject(JSON字符串)//JSON字符串转换成Java对象
JSONObject.parseObject(JSON字符串,Java对象.class)
工具包
com.alibaba druid-spring-boot-starter 1.1.20
com.alibaba fastjson 1.2.68
以及数据库连接池参数properties
server.port=10015# db
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/coding?useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.platform=mysql# druid
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
## \u5355\u4F4D\u662F\u6BEB\u79D2\uFF0C\u6B64\u5904\u8BBE\u7F6E\u4E3A2\u5206\u949F
spring.datasource.druid.max-wait=120000
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.pool-prepared-statements=true
## \u914D\u7F6E\u76D1\u63A7\u7EDF\u8BA1\u62E6\u622A\u7684filters\uFF0C\u53BB\u6389\u540E\u76D1\u63A7\u754C\u9762sql\u65E0\u6CD5\u7EDF\u8BA1\uFF0C'wall'\u7528\u4E8E\u9632\u706B\u5899
spring.datasource.druid.filters=stat,wall
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.druid.seGlobalDataSourceStat=true
spring.datasource.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
使用示例:
try {response = httpClient.execute(httpGet);//执行请求if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//请求成功执行HttpEntity entity = response.getEntity();//获取返回的数据String s = EntityUtils.toString(entity);//转换成字符串JSONObject datas = JSONObject.parseObject(s);//转换成JSON格式Integer status = (Integer) datas.get("status");//获取返回数据状态,get获取的字段需要根据提供的返回值去获取if (status == 200) {//返回的状态JSONObject data = JSONObject.parseObject(datas.get("data").toString());//"data"是根据返回值设定JSONObject jo = JSONObject.parseObject(data.toJSONString());JSONArray records = JSONObject.parseArray(jo.get("records").toString());//"records"是根据返回值设定return records;//返回的数据就是我需要去解析的}}} catch (IOException e) {e.printStackTrace();}
都是为了解决JSON字符串和其实体bean的属性名匹配不上的问题
区别:
混用可能会出现属性名匹配不上的问题
注解类型 | 依赖包 | bean转换成Json字符串 | Json字符串转化为bean |
---|---|---|---|
@JsonProperty | jackson | ObjectMapper().writeValueAsString(Object value) | ObjectMapper().readValue(String content, Class valueType) |
@JSONField | fastjson | JSONObject.toJSONString(Object value) | JSONObject.parseObject(String content, Class valueType) |