介紹:FastJson 是ailibaba 的一款解析Json的開源框架java
使用方式1json
引入jar 包框架
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>ide
@SpringBootApplication
//啓動類extends WebMvcConfigurerAdapter public class App extends WebMvcConfigurerAdapter{
//重寫configureMessageConverters @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig();
//是否須要格式化 fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastConverter.setFastJsonConfig(fastJsonConfig); converters.add(fastConverter); } public static void main(String[] args) { SpringApplication.run(App.class, args); } }
使用方式2spa
@SpringBootApplication public class App { //使用@Bean 依賴注入 @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); } public static void main(String[] args) { SpringApplication.run(App.class, args); } }
FastJson 其餘用法:code
格式化:orm
@JSONField(format = "yyyy-MM-dd")
private Date createDate;對象
自定義名稱:blog
@JSONField(name = "AGE")
private int age;
it
將 Java 對象轉換換爲 JSON 對象:
JSON.toJSONString()
建立JSON 對象:
public void whenGenerateJson_thanGenerationCorrect() throws ParseException { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < 2; i++) { JSONObject jsonObject = new JSONObject(); jsonObject.put("AGE", 10); jsonObject.put("FULL NAME", "Doe " + i); jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12"); jsonArray.add(jsonObject); } String jsonOutput = jsonArray.toJSONString(); }
JSON 對象須要轉java對象:
public void whenJson_thanConvertToObjectCorrect() { Person person = new Person(20, "John", "Doe", new Date()); String jsonObject = JSON.toJSONString(person); Person newPerson = JSON.parseObject(jsonObject, Person.class) }