题记: 项目中开始用是Gson,但是压力测试的时候会出现性能下降明显,不得已换成了fastjson
1.首先引用包
1 <dependency> 2 <groupId>com.alibaba</groupId> 3 <artifactId>fastjson</artifactId> 4 <version>1.2.41</version> 5 </dependency>
2.Application 添加@Bean
1 @Bean 2 public HttpMessageConverters fastJsonHttpMessageConverters(){ 3 //1.需要定义一个convert转换消息的对象; 4 FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); 5 //2:添加fastJson的配置信息; 6 FastJsonConfig fastJsonConfig = new FastJsonConfig(); 7 fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); 8 //3处理中文乱码问题 9 List<MediaType> fastMediaTypes = new ArrayList<>(); 10 fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); 11 //4.在convert中添加配置信息. 12 fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); 13 fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); 14 HttpMessageConverter<?> converter = fastJsonHttpMessageConverter; 15 return new HttpMessageConverters(converter); 16 17 }
3.实体注解写法 @JSONField(format="yyyy-MM-dd HH:mm:ss",name = "createTime")
1 @JSONField(format="yyyy-MM-dd HH:mm:ss",name = "createTime") 2 private Date createdDate; 3 @JSONField(name = "picture") 4 private String imageLink; 5 @JSONField(name = "playUrl") 6 private String mobileFileLink;
4.解析json字符串 {"msgId":"ed3ad9d5-005f-4e37-9f7b-fbaf7323d0ae","version":"2.0","timeStamp":1513233213925,"appId":"cms20001","type":"Article","action":"Delete","priority":"Normal","payload":{"entityid":"b3476954-67b0-474c-a7a7-f5f301dda46b","businessid":"6430523"}}
String t = new String(message,"UTF-8"); JSONObject jsonObj = JSON.parseObject(t) JSONObject payload = jsonObj.getJSONObject("payload"); long collectionId = payload.getLong("businessid");
针对array可以用这个
JSONObject jsonObj = new JSONObject(rawText); JSONArray jsonArray = result .getJSONArray("selList"); for (int i = 0; i < jsonArray.length; i++) { }