Spring boot FastJson

介绍:FastJson 是ailibaba 的一款解析Json的开源框架

 

使用方式1

引入jar 包

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.15</version>
</dependency>

 

@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); } }

 

 使用方式2

@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 其他用法:

格式化:

 @JSONField(format = "yyyy-MM-dd")
 private Date createDate;

 自定义名称:

@JSONField(name = "AGE")
  private int age;

 将 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)
}

 

转载于:https://www.cnblogs.com/pickKnow/p/10490822.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值