Search in sources :

Example 1 with FastJsonHttpMessageConverter

use of com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter in project spring-boot by Linda-Tan.

the class RestTemplateConfig method restTemplate.

@Bean("restTemplate")
@ConditionalOnMissingBean({ RestOperations.class, RestTemplate.class })
public RestTemplate restTemplate() {
    // http://rensanning.iteye.com/?page=3
    RestTemplate restTemplate = new RestTemplate(simpleClientHttpRequestFactory());
    restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
    return restTemplate;
}
Also used : RestTemplate(org.springframework.web.client.RestTemplate) FastJsonHttpMessageConverter(com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Bean(org.springframework.context.annotation.Bean)

Example 2 with FastJsonHttpMessageConverter

use of com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter in project spring-boot-api-seed-project by selfassu.

the class WebMvcConfigurer method configureMessageConverters.

// 设置 FastJson 作为 Json 对象的转换器
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    FastJsonConfig config = new FastJsonConfig();
    // 设置转换 json 之后的属性
    // SerializerFeature.WriteMapNullValue 保留空的字段
    config.setSerializerFeatures(SerializerFeature.WriteMapNullValue, // Number 类型为 null 直接转换成 0
    SerializerFeature.WriteNullNumberAsZero, // 字符串类型为 null 直接转换成 ""
    SerializerFeature.WriteNullStringAsEmpty, // 禁止循环引用
    SerializerFeature.DisableCircularReferenceDetect);
    // fastjson 版本过高的时候会报错
    // json java.lang.IllegalArgumentException: 'Content-Type' cannot contain wildcard type '*'
    // 需要自己指定 Content-Type , 老版本中默认指定的是 MediaType.ALL
    List<MediaType> mediaTypes = new ArrayList<>();
    mediaTypes.add(MediaType.APPLICATION_JSON);
    mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    mediaTypes.add(MediaType.APPLICATION_ATOM_XML);
    mediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
    mediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
    mediaTypes.add(MediaType.APPLICATION_PDF);
    mediaTypes.add(MediaType.APPLICATION_RSS_XML);
    mediaTypes.add(MediaType.APPLICATION_XHTML_XML);
    mediaTypes.add(MediaType.APPLICATION_XML);
    mediaTypes.add(MediaType.IMAGE_GIF);
    mediaTypes.add(MediaType.IMAGE_JPEG);
    mediaTypes.add(MediaType.IMAGE_PNG);
    mediaTypes.add(MediaType.TEXT_EVENT_STREAM);
    mediaTypes.add(MediaType.TEXT_HTML);
    mediaTypes.add(MediaType.TEXT_MARKDOWN);
    mediaTypes.add(MediaType.TEXT_PLAIN);
    mediaTypes.add(MediaType.TEXT_XML);
    converter.setSupportedMediaTypes(mediaTypes);
    converter.setFastJsonConfig(config);
    converter.setDefaultCharset(Charset.forName("UTF-8"));
    converters.add(converter);
}
Also used : FastJsonConfig(com.alibaba.fastjson.support.config.FastJsonConfig) ArrayList(java.util.ArrayList) FastJsonHttpMessageConverter(com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter) MediaType(org.springframework.http.MediaType)

Example 3 with FastJsonHttpMessageConverter

use of com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter in project fastjson by alibaba.

the class DateFormatPriorityTest method test_priority_01.

// Annotation + FastJsonConfig (Annotation优先)
public void test_priority_01() throws Exception {
    // FastJsonConfig
    FastJsonConfig config = new FastJsonConfig();
    config.setDateFormat("yyyy-MM.dd");
    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    converter.setFastJsonConfig(config);
    converter.canRead(VO.class, MediaType.APPLICATION_JSON_UTF8);
    converter.canWrite(VO.class, MediaType.APPLICATION_JSON_UTF8);
    final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    HttpOutputMessage out = new HttpOutputMessage() {

        public HttpHeaders getHeaders() {
            return new HttpHeaders() {

                private static final long serialVersionUID = 1L;

                @Override
                public MediaType getContentType() {
                    return MediaType.APPLICATION_JSON;
                }
            };
        }

        public OutputStream getBody() throws IOException {
            return byteOut;
        }
    };
    VO2 vo = new VO2();
    vo.setDate(calendar.getTime());
    converter.write(vo, VO.class, MediaType.APPLICATION_JSON_UTF8, out);
    byte[] bytes = byteOut.toByteArray();
    String jsonString = new String(bytes, "UTF-8");
    assertEquals("{\"date\":\"1995.10-26\"}", jsonString);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) FastJsonConfig(com.alibaba.fastjson.support.config.FastJsonConfig) HttpOutputMessage(org.springframework.http.HttpOutputMessage) FastJsonHttpMessageConverter(com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 4 with FastJsonHttpMessageConverter

use of com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter in project fastjson by alibaba.

the class FastJsonHttpMessageConverterTest method test_read.

@SuppressWarnings("deprecation")
public void test_read() throws Exception {
    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    converter.setCharset(Charset.forName("UTF-8"));
    Assert.assertEquals(Charset.forName("UTF-8"), converter.getCharset());
    converter.setFeatures(SerializerFeature.BrowserCompatible);
    Assert.assertEquals(1, converter.getFeatures().length);
    Assert.assertEquals(SerializerFeature.BrowserCompatible, converter.getFeatures()[0]);
    Assert.assertNull(converter.getDateFormat());
    converter.setDateFormat("yyyyMMdd");
    converter.setFilters(serializeFilter);
    Assert.assertEquals(1, converter.getFilters().length);
    Assert.assertEquals(serializeFilter, converter.getFilters()[0]);
    converter.addSerializeFilter(serializeFilter);
    Assert.assertEquals(2, converter.getFilters().length);
    converter.addSerializeFilter(null);
    converter.setSupportedMediaTypes(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON_UTF8 }));
    Assert.assertEquals(1, converter.getSupportedMediaTypes().size());
    Method method = FastJsonHttpMessageConverter.class.getDeclaredMethod("supports", Class.class);
    method.setAccessible(true);
    method.invoke(converter, int.class);
    HttpInputMessage input = new HttpInputMessage() {

        public HttpHeaders getHeaders() {
            // TODO Auto-generated method stub
            return null;
        }

        public InputStream getBody() throws IOException {
            return new ByteArrayInputStream("{\"id\":123}".getBytes(Charset.forName("UTF-8")));
        }
    };
    VO vo = (VO) converter.read(VO.class, input);
    Assert.assertEquals(123, vo.getId());
    final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    HttpOutputMessage out = new HttpOutputMessage() {

        public HttpHeaders getHeaders() {
            return new HttpHeaders();
        }

        public OutputStream getBody() throws IOException {
            return byteOut;
        }
    };
    converter.write(vo, MediaType.TEXT_PLAIN, out);
    byte[] bytes = byteOut.toByteArray();
    Assert.assertEquals("{\"id\":\"123\"}", new String(bytes, "UTF-8"));
}
Also used : HttpInputMessage(org.springframework.http.HttpInputMessage) HttpHeaders(org.springframework.http.HttpHeaders) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpOutputMessage(org.springframework.http.HttpOutputMessage) FastJsonHttpMessageConverter(com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter) MediaType(org.springframework.http.MediaType) Method(java.lang.reflect.Method) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 5 with FastJsonHttpMessageConverter

use of com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter in project fastjson by alibaba.

the class Issue3805 method test.

@Test
public void test() throws Exception {
    String dateFormat = "yyyy";
    TestModel model = new TestModel();
    model.setCreateTime(LocalDateTime.of(2021, 5, 6, 7, 8, 9, 5));
    FastJsonConfig config = new FastJsonConfig();
    config.setDateFormat(dateFormat);
    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    converter.setFastJsonConfig(config);
    converter.canRead(TestModel.class, MediaType.APPLICATION_JSON_UTF8);
    converter.canWrite(TestModel.class, MediaType.APPLICATION_JSON_UTF8);
    final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    HttpOutputMessage out = new HttpOutputMessage() {

        public HttpHeaders getHeaders() {
            return new HttpHeaders() {

                private static final long serialVersionUID = 1L;

                @Override
                public MediaType getContentType() {
                    return MediaType.APPLICATION_JSON;
                }
            };
        }

        public OutputStream getBody() throws IOException {
            return byteOut;
        }
    };
    converter.write(model, TestModel.class, MediaType.APPLICATION_JSON_UTF8, out);
    byte[] bytes = byteOut.toByteArray();
    String jsonString = new String(bytes, "UTF-8");
    // System.out.println(jsonString);
    Assert.assertEquals(jsonString, "{\"createTime\":\"2021\"}");
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) FastJsonConfig(com.alibaba.fastjson.support.config.FastJsonConfig) HttpOutputMessage(org.springframework.http.HttpOutputMessage) FastJsonHttpMessageConverter(com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Test(org.junit.Test)

Aggregations

FastJsonHttpMessageConverter (com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter)12 FastJsonConfig (com.alibaba.fastjson.support.config.FastJsonConfig)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 HttpHeaders (org.springframework.http.HttpHeaders)5 HttpOutputMessage (org.springframework.http.HttpOutputMessage)5 Bean (org.springframework.context.annotation.Bean)4 MediaType (org.springframework.http.MediaType)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ArrayList (java.util.ArrayList)2 ConditionalOnMissingBean (org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean)2 HttpMessageConverters (org.springframework.boot.autoconfigure.web.HttpMessageConverters)2 HttpInputMessage (org.springframework.http.HttpInputMessage)2 RestTemplate (org.springframework.web.client.RestTemplate)2 SerializeConfig (com.alibaba.fastjson.serializer.SerializeConfig)1 SimpleDateFormatSerializer (com.alibaba.fastjson.serializer.SimpleDateFormatSerializer)1 Method (java.lang.reflect.Method)1 Test (org.junit.Test)1