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
43 lines (41 loc) · 1.86 KB
/
CodegenImplMap.java
File metadata and controls
43 lines (41 loc) · 1.86 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
package com.jsoniter.output;
import java.lang.reflect.Type;
class CodegenImplMap {
public static CodegenResult genMap(Class clazz, Type[] typeArgs) {
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(':');
CodegenImplNative.genWriteOp(ctx, "entry.getValue()", valueType);
ctx.append("while(iter.hasNext()) {");
ctx.append("entry = (java.util.Map.Entry)iter.next();");
ctx.buffer(',');
ctx.append("stream.writeObjectField((String)entry.getKey());");
CodegenImplNative.genWriteOp(ctx, "entry.getValue()", valueType);
ctx.append("}");
ctx.buffer('}');
ctx.append("}");
return ctx;
}
}