forked from json-iterator/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapKeyEncoders.java
More file actions
78 lines (65 loc) · 2.46 KB
/
MapKeyEncoders.java
File metadata and controls
78 lines (65 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.jsoniter.output;
import com.jsoniter.spi.*;
import java.io.IOException;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
class MapKeyEncoders {
public static Encoder registerOrGetExisting(Type mapKeyType) {
String cacheKey = JsoniterSpi.getMapKeyEncoderCacheKey(mapKeyType);
Encoder mapKeyEncoder = JsoniterSpi.getMapKeyEncoder(cacheKey);
if (null != mapKeyEncoder) {
return mapKeyEncoder;
}
mapKeyEncoder = createDefaultEncoder(mapKeyType);
JsoniterSpi.addNewMapEncoder(cacheKey, mapKeyEncoder);
return mapKeyEncoder;
}
private static Encoder createDefaultEncoder(Type mapKeyType) {
if (mapKeyType == String.class) {
return new StringKeyEncoder();
}
if (mapKeyType == Object.class) {
return new DynamicKeyEncoder();
}
if (mapKeyType instanceof WildcardType) {
return new DynamicKeyEncoder();
}
if (mapKeyType instanceof Class && ((Class) mapKeyType).isEnum()) {
return new StringKeyEncoder();
}
Encoder.ReflectionEncoder encoder = CodegenImplNative.NATIVE_ENCODERS.get(mapKeyType);
if (encoder != null) {
return new NumberKeyEncoder(encoder);
}
throw new JsonException("can not encode map key type: " + mapKeyType);
}
private static class StringKeyEncoder implements Encoder {
@Override
public void encode(Object obj, JsonStream stream) throws IOException {
stream.writeVal(obj);
}
}
private static class NumberKeyEncoder implements Encoder {
private final Encoder encoder;
private NumberKeyEncoder(Encoder encoder) {
this.encoder = encoder;
}
@Override
public void encode(Object obj, JsonStream stream) throws IOException {
stream.write('"');
encoder.encode(obj, stream);
stream.write('"');
}
}
private static class DynamicKeyEncoder implements Encoder {
@Override
public void encode(Object obj, JsonStream stream) throws IOException {
Class<?> clazz = obj.getClass();
if (clazz == Object.class) {
throw new JsonException("map key type is Object.class, can not be encoded");
}
Encoder mapKeyEncoder = registerOrGetExisting(clazz);
mapKeyEncoder.encode(obj, stream);
}
}
}