forked from json-iterator/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodegenImplMap.java
More file actions
60 lines (58 loc) · 2.62 KB
/
CodegenImplMap.java
File metadata and controls
60 lines (58 loc) · 2.62 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
package com.jsoniter.output;
import java.lang.reflect.Type;
import java.util.Collection;
class CodegenImplMap {
public static CodegenResult genMap(String cacheKey, Class clazz, Type[] typeArgs) {
boolean isCollectionValueNullable = true;
if (cacheKey.endsWith("__value_not_nullable")) {
isCollectionValueNullable = false;
}
Type keyType = String.class;
Type valueType = Object.class;
if (typeArgs.length == 0) {
// default to Map<String, Object>
} else if (typeArgs.length == 2) {
keyType = typeArgs[0];
valueType = typeArgs[1];
} else {
throw new IllegalArgumentException(
"can not bind to generic collection without argument types, " +
"try syntax like TypeLiteral<Map<String, String>>{}");
}
if (keyType != String.class) {
throw new IllegalArgumentException("map key must be String");
}
CodegenResult ctx = new CodegenResult();
ctx.append("public static void encode_(java.lang.Object obj, com.jsoniter.output.JsonStream stream) throws java.io.IOException {");
ctx.append("if (obj == null) { stream.writeNull(); return; }");
ctx.append("java.util.Map map = (java.util.Map)obj;");
ctx.append("java.util.Iterator iter = map.entrySet().iterator();");
ctx.append("if(!iter.hasNext()) { return; }");
ctx.append("java.util.Map.Entry entry = (java.util.Map.Entry)iter.next();");
ctx.buffer('{');
ctx.append("stream.writeVal((String)entry.getKey());");
ctx.buffer(':');
if (isCollectionValueNullable) {
ctx.append("if (entry.getValue() == null) { stream.writeNull(); } else {");
CodegenImplNative.genWriteOp(ctx, "entry.getValue()", valueType, true);
ctx.append("}");
} else {
CodegenImplNative.genWriteOp(ctx, "entry.getValue()", valueType, false);
}
ctx.append("while(iter.hasNext()) {");
ctx.append("entry = (java.util.Map.Entry)iter.next();");
ctx.buffer(',');
ctx.append("stream.writeObjectField((String)entry.getKey());");
if (isCollectionValueNullable) {
ctx.append("if (entry.getValue() == null) { stream.writeNull(); } else {");
CodegenImplNative.genWriteOp(ctx, "entry.getValue()", valueType, true);
ctx.append("}");
} else {
CodegenImplNative.genWriteOp(ctx, "entry.getValue()", valueType, false);
}
ctx.append("}");
ctx.buffer('}');
ctx.append("}");
return ctx;
}
}