1 package com.foxinmy.weixin4j.http.message;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5
6 import com.alibaba.fastjson.JSON;
7 import com.foxinmy.weixin4j.http.HttpHeaders;
8 import com.foxinmy.weixin4j.http.HttpResponse;
9 import com.foxinmy.weixin4j.http.MimeType;
10 import com.foxinmy.weixin4j.util.FileUtil;
11 import com.foxinmy.weixin4j.util.IOUtil;
12 import com.foxinmy.weixin4j.util.RegexUtil;
13
14
15
16
17
18
19
20
21
22 public class JsonMessageConverter extends AbstractMessageConverter {
23
24 public static final JsonMessageConverter GLOBAL = new JsonMessageConverter();
25
26 private static final String JSO = "json";
27 private static final int BRACE = 1 << '{';
28 private static final int BRACKET = 1 << '[';
29 private static final int MASK = BRACE | BRACKET;
30
31 public JsonMessageConverter() {
32 super(MimeType.APPLICATION_JSON, MimeType.TEXT_JSON, new MimeType(
33 "application", "*+json"));
34 }
35
36 @Override
37 public boolean canConvert(Class<?> clazz, HttpResponse response) {
38 if (!super.canConvert(clazz, response)) {
39 String disposition = response.getHeaders().getFirst(
40 HttpHeaders.CONTENT_DISPOSITION);
41 String fileName = RegexUtil
42 .regexFileNameFromContentDispositionHeader(disposition);
43 return (fileName != null && FileUtil.getFileExtension(fileName)
44 .equalsIgnoreCase(JSO));
45 }
46 return true;
47 }
48
49 @Override
50 protected boolean supports(Class<?> clazz, byte[] content) {
51 return (MASK & (1 << content[0])) != 0;
52 }
53
54 @Override
55 protected <T> T convertInternal(Class<? extends T> clazz, InputStream body)
56 throws IOException {
57 byte[] bytes = IOUtil.toByteArray(body);
58 return JSON.parseObject(bytes, 0, bytes.length, charset.newDecoder(),
59 clazz);
60 }
61 }