题记: 项目中开始用是Gson,但是压力测试的时候会出现性能下降明显,不得已换成了fastjson
1.首先引用包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
2.Application 添加@Bean
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters(){
//1.需要定义一个convert转换消息的对象;
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//2:添加fastJson的配置信息;
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//3处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
//4.在convert中添加配置信息.
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
return new HttpMessageConverters(converter); }
3.实体注解写法 @JSONField(format=”yyyy-MM-dd HH:mm:ss”,name = “createTime”)
@JSONField(format="yyyy-MM-dd HH:mm:ss",name = "createTime")
private Date createdDate;
@JSONField(name = "picture")
private String imageLink;
@JSONField(name = "playUrl")
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++) { }