Skip to content

Commit 91093ff

Browse files
committed
Add optional omit zero in dynamic codegen
1 parent 743093a commit 91093ff

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

src/main/java/com/jsoniter/output/CodegenImplObject.java

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ private static int genField(CodegenResult ctx, Binding binding, String toName, i
8787
isCollectionValueNullable = true;
8888
}
8989
boolean nullable = !valueClazz.isPrimitive();
90+
boolean omitZero = JsoniterSpi.getCurrentConfig().omitZero();
9091
if (!binding.isNullable) {
9192
nullable = false;
9293
}
@@ -108,19 +109,30 @@ private static int genField(CodegenResult ctx, Binding binding, String toName, i
108109
ctx.append(String.format("if (%s == null) { stream.writeNull(); } else {", valueAccessor));
109110
}
110111
} else {
111-
notFirst = appendComma(ctx, notFirst);
112-
ctx.buffer('"');
113-
ctx.buffer(toName);
114-
ctx.buffer('"');
115-
ctx.buffer(':');
112+
if (encoder == null && valueClazz.isPrimitive() && !(valueClazz == String.class) && omitZero) {
113+
if (notFirst == 0) {
114+
notFirst = 2;
115+
ctx.append("boolean notFirst = false;");
116+
}
117+
String t = CodegenImplNative.getTypeName(binding.valueType);
118+
ctx.append(String.format("if (!(((%s)%s) == 0)) {", t, valueAccessor));
119+
appendComma(ctx, notFirst);
120+
ctx.append(CodegenResult.bufferToWriteOp("\"" + toName + "\":"));
121+
} else {
122+
notFirst = appendComma(ctx, notFirst);
123+
ctx.buffer('"');
124+
ctx.buffer(toName);
125+
ctx.buffer('"');
126+
ctx.buffer(':');
127+
}
116128
}
117129
if (encoder == null) {
118130
CodegenImplNative.genWriteOp(ctx, valueAccessor, binding.valueType, nullable, isCollectionValueNullable);
119131
} else {
120132
ctx.append(String.format("com.jsoniter.output.CodegenAccess.writeVal(\"%s\", %s, stream);",
121133
fieldCacheKey, valueAccessor));
122134
}
123-
if (nullable) {
135+
if (nullable || omitZero) {
124136
ctx.append("}");
125137
}
126138
return notFirst;

0 commit comments

Comments
 (0)