提交 | 用户 | 时间
|
722af2
|
1 |
package com.dl.common.translation.handler; |
X |
2 |
|
|
3 |
import cn.hutool.core.util.ObjectUtil; |
|
4 |
import com.fasterxml.jackson.core.JsonGenerator; |
|
5 |
import com.fasterxml.jackson.databind.BeanProperty; |
|
6 |
import com.fasterxml.jackson.databind.JsonMappingException; |
|
7 |
import com.fasterxml.jackson.databind.JsonSerializer; |
|
8 |
import com.fasterxml.jackson.databind.SerializerProvider; |
|
9 |
import com.fasterxml.jackson.databind.ser.ContextualSerializer; |
|
10 |
import com.dl.common.annotation.Translation; |
|
11 |
import com.dl.common.translation.TranslationInterface; |
|
12 |
import com.dl.common.utils.StringUtils; |
|
13 |
import com.dl.common.utils.reflect.ReflectUtils; |
|
14 |
import lombok.extern.slf4j.Slf4j; |
|
15 |
|
|
16 |
import java.io.IOException; |
|
17 |
import java.util.Map; |
|
18 |
import java.util.Objects; |
|
19 |
import java.util.concurrent.ConcurrentHashMap; |
|
20 |
|
|
21 |
/** |
|
22 |
* 翻译处理器 |
|
23 |
* |
|
24 |
* @author Lion Li |
|
25 |
*/ |
|
26 |
@Slf4j |
|
27 |
public class TranslationHandler extends JsonSerializer<Object> implements ContextualSerializer { |
|
28 |
|
|
29 |
/** |
|
30 |
* 全局翻译实现类映射器 |
|
31 |
*/ |
|
32 |
public static final Map<String, TranslationInterface<?>> TRANSLATION_MAPPER = new ConcurrentHashMap<>(); |
|
33 |
|
|
34 |
private Translation translation; |
|
35 |
|
|
36 |
@Override |
|
37 |
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException { |
|
38 |
TranslationInterface<?> trans = TRANSLATION_MAPPER.get(translation.type()); |
|
39 |
if (ObjectUtil.isNotNull(trans)) { |
|
40 |
// 如果映射字段不为空 则取映射字段的值 |
|
41 |
if (StringUtils.isNotBlank(translation.mapper())) { |
|
42 |
value = ReflectUtils.invokeGetter(gen.getCurrentValue(), translation.mapper()); |
|
43 |
} |
|
44 |
// 如果为 null 直接写出 |
|
45 |
if (ObjectUtil.isNull(value)) { |
|
46 |
gen.writeNull(); |
|
47 |
return; |
|
48 |
} |
|
49 |
Object result = trans.translation(value, translation.other()); |
|
50 |
gen.writeObject(result); |
|
51 |
} else { |
|
52 |
gen.writeObject(value); |
|
53 |
} |
|
54 |
} |
|
55 |
|
|
56 |
@Override |
|
57 |
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException { |
|
58 |
Translation translation = property.getAnnotation(Translation.class); |
|
59 |
if (Objects.nonNull(translation)) { |
|
60 |
this.translation = translation; |
|
61 |
return this; |
|
62 |
} |
|
63 |
return prov.findValueSerializer(property.getType(), property); |
|
64 |
} |
|
65 |
} |