
com.jsoniter.output.ReflectionMapEncoder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jsoniter Show documentation
Show all versions of jsoniter Show documentation
jsoniter (json-iterator) is fast and flexible JSON parser available in Java and Go
package com.jsoniter.output;
import com.jsoniter.any.Any;
import com.jsoniter.spi.Encoder;
import com.jsoniter.spi.TypeLiteral;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
class ReflectionMapEncoder implements Encoder {
private final TypeLiteral valueTypeLiteral;
public ReflectionMapEncoder(Class clazz, Type[] typeArgs) {
if (typeArgs.length > 1) {
valueTypeLiteral = TypeLiteral.create(typeArgs[1]);
} else {
valueTypeLiteral = TypeLiteral.create(Object.class);
}
}
@Override
public void encode(Object obj, JsonStream stream) throws IOException {
if (obj == null) {
stream.writeNull();
return;
}
Map map = (Map) obj;
stream.writeObjectStart();
boolean notFirst = false;
for (Map.Entry entry : map.entrySet()) {
if (notFirst) {
stream.writeMore();
} else {
notFirst = true;
}
stream.writeObjectField(entry.getKey());
stream.writeVal(valueTypeLiteral, entry.getValue());
}
stream.writeObjectEnd();
}
@Override
public Any wrap(Object obj) {
Map map = (Map) obj;
Map copied = new HashMap();
for (Map.Entry entry : map.entrySet()) {
copied.put(entry.getKey(), JsonStream.wrap(entry.getValue()));
}
return Any.wrapAnyMap(copied);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy